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!
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)