0

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?

2
  • A way to find out how and whether the methods function as you need, is to try the code with both methods and see/compare the results. You can include some debug statements in your code (console.log(...)) to understand how the code flows. Commented May 16, 2024 at 11:03
  • 1
    The second one should use writeFileSync. Or better: use fs/promises. Commented May 16, 2024 at 11:04

1 Answer 1

0

fs.writeFile is async. As a result the main difference between to methods is that,

  • Method 1 waits for the file write operation to complete before sending the response.
  • Method 2 sends the response immediately, regardless of whether the file write operation has completed or not.

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.