-1

This is the code snippet. The query returns in json form but how do I write these values in a JSON file?

app.get('/users', function(req, res) {
    User.find({}, function(err, docs) {
        res.json(docs);

        console.error(err);
    })
});
1
  • 4
    have you tried using fs? Commented Apr 10, 2017 at 19:09

2 Answers 2

1

If you're going to be writing to a file within a route callback handler you should use the Asynchronous writeFile() function or the fs.createWriteStream() function which are a part of the fs Module in the Node.js Core API . If not, your server will be unresponsive to any subsequent requests because the Node.js thread will be blocking while it is writing to the file system.

Here is an example usage of writeFile within your route callback handler. This code will overwrite the ./docs.json file every time the route is called.

const fs = require('fs')
const filepath = './docs.json'

app.get('/users', (req, res) => {
    Users.find({}, (err, docs) => {
      if (err)
        return res.sendStatus(500)

      fs.writeFile(filepath, JSON.stringify(docs, null, 2), err => {
        if (err)
          return res.sendStatus(500)

        return res.json(docs)
      })
    })
})

Here is an example usage of writing your JSON to a file with Streams. fs.createReadStream() is used to create a readable stream of the stringified docs object. Then that Readable is written to the filepath with a Writable stream that has the Readable data piped into it.

const fs = require('fs')

app.get('/users', (req, res) => {
    Users.find({}, (err, docs) => {
      if (err)
        return res.sendStatus(500)

      let reader = fs.createReadStream(JSON.stringify(docs, null, 2))
      let writer = fs.createWriteStream(filename)

      reader.on('error', err => {
        // an error occurred while reading
        writer.end()  // explicitly close writer
        return res.sendStatus(500)
      })

      write.on('error', err => {
        // an error occurred writing
        return res.sendStatus(500)
      })

      write.on('close', () => {
        // writer is done writing the file contents, respond to requester
        return res.json(docs)
      })

      // pipe the data from reader to writer
      reader.pipe(writer)
    })
})
Sign up to request clarification or add additional context in comments.

3 Comments

Would love to know the downvote since there is nothing wrong with this answer.
I didn't downvote, but I wonder if an error in the readable stream would trigger a leak of the file writer stream, as explained here: "One important caveat is that if the Readable stream emits an error during processing, the Writable destination is not closed automatically. If an error occurs, it will be necessary to manually close each stream in order to prevent memory leaks."
@E_net4 added explicit closing of writer in the event an error during reading.
0

Use node's file system library 'fs'.

const fs = require('fs');

const jsonData = { "Hello": "World" };
fs.writeFileSync('output.json', JSON.strigify(jsonData));

Docs: fs.writeFileSync(file, data[, options])

2 Comments

This answer won't work since you cannot directly write a JS object to a file without stringifying it first.
I've updated the code to pass a string version of the JSON using JSON.stringify()

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.