在nodejs中使用请求编写文本文件

时间:2016-06-29 16:29:45

标签: node.js

我一直在尝试从URL读取txt文件并使用nodejs输出我自己的文本文件

有谁能告诉我我的代码中出错了什么?

var fs = require('fs');
var request = require('request');
var stream = fs.createWriteStream("my_file.txt");



request('http://redsismica.uprm.edu/Data/prsn/EarlyWarning/Catalogue.txt', function (error, response, body) {
  if (!error && response.statusCode == 200) {

    firstLine = body.substring(0, body.indexOf('\n'));
    console.log(firstLine);

    stream.once('open', function(fd) {
    wstream.write(firstLine, 'utf16le');//stream.write(firstLine);
    stream.end();
});
  }
})

1 个答案:

答案 0 :(得分:2)

不确定代码中wstream的内容是request you can pipe your response directly to your write stream.

var stream = fs.createWriteStream('my_file.txt', { defaultEncoding: 'utf16le' });

stream.once('error', function(err) {
  console.log(err);
});

stream.once('end', function() {
  console.log('response written');
});

request('http://redsismica.uprm.edu/Data/prsn/EarlyWarning/Catalogue.txt')
  .once('error', function(err) {
    console.log('Request Error: ' + err);
  })
  .pipe(stream);