使用Node.js

时间:2018-06-13 23:03:22

标签: javascript node.js

我是Node新手并尝试从服务器请求一些json数据并保存到文件中。我可以接收数据没问题,但是一旦收到所有数据就无法解决如何写入文件。我需要回调还是需要使用http.CreateServer()?任何帮助都将不胜感激。

这是我到目前为止所做的:

"use strict";

const request = require('request');
const fs = require('fs');

var options = {
    url: 'url-to-request-data',
    method: 'GET',
    accept: 'application/json',
    json: true,} 
};

// Start the request
request(options, function(error, response, body) {
  if (error) { 
      return console.log(error); 
  } else {
        var path = "~/jsonfile.json";
        fs.writeFile(path, body);
  }
  });

2 个答案:

答案 0 :(得分:2)

你有几个问题。

fs.writeFile接受第三个参数,一个回调函数,它会通知你任何错误,你得到的。

fs.writeFile(path, body, err => console.error(err));

在具有该文件路径的* nix系统上,您将获得Error: ENOENT: no such file or directory

~是一个bash扩展,节点不知道如何处理它。

使用:

const os = require('os');
const path = require('path');

const filePath = path.join(os.homedir(), 'jsonfile.json');
fs.writeFile(path, body, err => console.error(err));

然后,如果该网址返回[Object object],您将~/jsonfile.json写入json,因为您明确要求提供。{/ p>

你需要解决方案:

  1. 删除json: true
  2. fs.writeFile(path, JSON.stringify(body), err => /* ... */)
  3. 如果您只是写一个文件,最好的方法是使用streams

    const filePath = path.join(os.homedir(), 'jsonfile.json');
    request(options).pipe(fs.createWriteStream(filePath));
    // See link for error handling
    

    您可以详细了解request和流,以及如何处理here中的错误

答案 1 :(得分:1)

  

json数据非常大,fs.writeFileSync是最好的方法吗? - ozzyzig

没有。您应该为大文件创建Writable Stream,这样您只能在内存中缓冲一块数据,而不是一次缓冲整个文件。 request()返回一个实现Stream界面的对象,因此您只需.pipe()将其转换为fs.createWriteStream()

'use strict';

const request = require('request');
const fs = require('fs');

var options = {
  url: 'url-to-request-data',
  method: 'GET',
  accept: 'application/json',
  // json: true,
};
var path = '~/jsonfile.json';
var ws = fs.createWriteStream(path);

// Start the request
request(options).on('error', function (error) {
  console.log(error);
}).on('close', function () {
  console.log('Done');
}).pipe(ws);