如何使用JSON字符串化网站的响应并将其保存到文件中 [英] How can I JSON stringify the response of a website and save it to a file
问题描述
如何用JSON字符串化网站的响应并使用FS将JSON字符串化的响应保存到文件中?
How can I JSON stringify the response of a website and use FS to save the JSON stringified response to a file?
这是我的代码,但未转换为JSON:
This is my code but it didn't convert to JSON:
var request = require("request")
var fs = require('fs');
var url = "http://rubycp.me/"
var http = require('http');
var file = fs.createWriteStream("file.json");
var url = http.get("http://rubycp.me/", function(response) {
JSON.stringify(response.pipe(file));
});
我只是想将页面的html转换为JSON并将其存储 放入json文件.
I simply want to convert the html of the page into JSON and store that into a json file.
推荐答案
response
是不保存任何数据的流对象.您首先需要使用data
事件收集流的所有数据.如果所有数据都已收集,则会触发end
事件,即使您可以对收集的数据进行字符串化并将其写入文件.
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
})
})
这篇关于如何使用JSON字符串化网站的响应并将其保存到文件中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!