如何使用JSON字符串化网站的响应并将其保存到文件中 [英] How can I JSON stringify the response of a website and save it to a file

查看:195
本文介绍了如何使用JSON字符串化网站的响应并将其保存到文件中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何用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屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆