Working with fs in node. Why won't this work?

Hello,
I’m trying to read a json file in my auth code with the following fs snippet.

const fs = require('fs');
const posts = fs.readFile("../posts.json", (data) => {
  let json = JSON.parse(data.posts);
});

The reason I’m trying it with data.posts is because posts is an array within a object. Here is the sytnax of my json file to explain.

{
  "posts": [
    {
      "title": "popcorn",
      "description": "popcorn is very good"
    }
  ]
}

With this code I get the following error

SyntaxError: Unexpected token E in JSON at position 0
    at JSON.parse (<anonymous>)

Any suggestions? Thanks in advance!!!

Hi,

There are a couple of things to be aware of:

  • The callback should have an err argument
  • If no encoding is specified, then readFile returns a raw buffer
  • If we specify an encoding, readFile will return a string. A string won’t have a posts property.

That said, something like this should work:

const fs = require('fs');

fs.readFile('../posts.json', 'utf8', (err, data) => {
  const json = JSON.parse(data);
  console.log(json.posts);
});

Gives you:

[ { title: 'popcorn', description: 'popcorn is very good' } ]
1 Like

This is great! However, how can I use the const json outside the fs.readFile? I need to pass it into my authentication function. It doesn’t seem to work currently because it believes it is undefined as the const json is only in the readFile. I apologize if this edit seems commonsense, I am new to node. Thanks again!

const fs = require('fs');

fs.readFile('../posts.json', 'utf8', (err, data) => {
  const json = JSON.parse(data);
  console.log(json.posts);
});

Assuming (as per one of your previous topics) that this authentication function is an express middleware, you can’t pass it directly; however you might write another middleware that adds the posts to the request object before calling next(), so later it will be available to the authentication middleware as well:

app.use((req, res, next) => {
  fs.readFile('../posts.json', (err, data) => {
    if (err) {
      return next(err)
    }

    req.posts = JSON.parse(data).posts
    next()
  })
})

// basicAuth has now access to req.posts
app.use(basicAuth)

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.