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
})
})
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…