-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);
    })
});
Przemek
  • 3,855
  • 2
  • 25
  • 33

2 Answers2

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)
    })
})
peteb
  • 18,552
  • 9
  • 50
  • 62
  • Would love to know the downvote since there is nothing wrong with this answer. – peteb Apr 10 '17 at 20:13
  • 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](https://nodejs.org/api/stream.html#stream_readable_pipe_destination_options): "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 Apr 10 '17 at 20:32
  • @E_net4 added explicit closing of writer in the event an error during reading. – peteb Apr 10 '17 at 20:36
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])

Rob Brander
  • 3,702
  • 1
  • 20
  • 33