[Solved] How can I JSON stringify the response of a website and save it to a file


response is a stream object that does not hold any data. You first need to collect all the data of the stream using the data event. If all data is collect the end event is triggered, at that even you can stringify your collected data and write it to the file.

const fs = require('fs')
const http = require('http')

var url="http://rubycp.me/"

var file = fs.createWriteStream('file.json')

http.get(url, response => {
  // list that will hold all received chunks
  var result = []
  response
    .on('data', chunk => result.push(chunk)) // add received chunk to list
    .on('end', () => {
      file.write(JSON.stringify(Buffer.concat(result).toString())) // when all chunks are received concat, stringify and write it to the file
    })
})

1

solved How can I JSON stringify the response of a website and save it to a file