I am trying to declare a POST
method for a RESTful API using node and express. I need to accept the request body and write it onto a JSON file that I'm using to store my users data. I am using the fs
module to modify the JSON file.
I have written the same code with a slight difference in declaring the return statement.
Method 1-
app.post('/api/users', (req, res) => {
const body = req.body;
users.push(body)
fs.writeFile("./users.json", JSON.stringify(users), (err) => {
if (err) {
console.log(err)
}
return res.json({ status: 'success', data: body });
})
})
Method 2-
app.post('/api/users', (req, res) => {
const body = req.body;
users.push(body)
fs.writeFile("./users.json", JSON.stringify(users), (err) => {
if (err) {
console.log(err)
}
})
return res.json({ status: 'success', data: body });
})
As per what I understand, the return statement in Method 1 is meant for the callback
fn parameter of the fs
method writeFile
. Whereas the return statement in Method 2 is explicitly defined for the request handler
fn for the POST
method. And res.send()
is used with the req. handler fn.
Is there any difference between these two methods? Which one is the correct way? Do they essentially perform the same function?
fs.writeFile
is async. As a result the main difference between to methods is that,
Method 1 is safer, but potentially slower.
It does not matter what you will return
from request handler and fs.writeFile callback (in method 1 or 2). Both:
fs.writeFile
callback, and express request handlers ignores the return value.