如何使用nodejs创建一个带缓冲区的读取流

时间:2016-06-15 11:13:37

标签: node.js google-bigquery fs

我有这个json:

var myJSON = '{"kind": "person", "fullName": "Rivka3"}';

我正在尝试使用createReadStream将其上传到bigquery。 当我保存它时,我成功了:

fs.writeFile("/tmp/bq_json_file_new.json", myJSON, function(err){});
fs.createReadStream("/tmp/bq_json_file_new.json")
  .pipe(table.createWriteStream(metadata))
  .on('complete', function(job) {
    job
      .on('error', console.log)
      .on('complete', function(metadata) {
        console.log('job completed', metadata);
      });
  });

现在我正在尝试这样做,而不是使用缓冲区保存它:

fs.createReadStream(new Buffer(myJSON, "utf8"))
  .pipe(table.createWriteStream(metadata))
  .on('complete', function(job) {
    job
      .on('error', console.log)
      .on('complete', function(metadata) {
        console.log('job completed', metadata);
      });
  });

但是我收到了这个错误:

fs.js:575
  binding.open(pathModule._makeLong(path),

TypeError: path must be a string

1 个答案:

答案 0 :(得分:18)

使用stream解决了问题:

var stream = require('stream');

var bufferStream = new stream.PassThrough();

bufferStream.end(new Buffer(myJSON));

bufferStream.pipe(table.createWriteStream(metadata))
                   .on('complete', function(job) {
                     job
                       .on('error', console.log)
                       .on('complete', function(metadata) {
                         console.log('job completed', metadata);
                       });
                   });