NodeJS 节点js可读流管道使用可写流到文件

jpfvwuh4  于 2022-12-18  发布在  Node.js
关注(0)|答案(1)|浏览(122)

我尝试用pipeTo将一个上传到nodejs 18.12.的ReadableStream文件写入硬盘上的文件。

const fs = require('fs');
var path = __dirname + '/test.png';
const writeStream = fs.createWriteStream(path);
// stream is a ReadableStream object
stream.pipeTo(writeStream).on('finish', async () => {
      console.log('DONE');
})

TypeError: ReadableStream.prototype.pipeTo's first argument must be a WritableStream

但是我还没有找到任何关于如何正确使用pipeTo并将数据存储到文件中的文档。搜索WritableStream也没有帮助我。我使用的是graphql-yoga 3.x,ReadableStream是我从框架中得到的。
我还尝试了here中的解决方案,将流转换为Readable

const { Readable } = require('node:stream');
var readStream = new Readable().wrap(stream);


失败的代码为stream.on is not a function
我还尝试了here的Readable.fromWeb解决方案

const writeStream = fs.createWriteStream(path);
var readStream = Readable.fromWeb(stream);
readStream.pipe(writeStream).on('finish', async () => {
  console.log('DONE');
})

这让我犯了一个奇怪的错误

TypeError: The "readableStream" argument must be an instance of ReadableStream. 
Received an instance of ReadableStream

我现在也在graphql yoga网站上找到了一个example的v2版本,但是它也不起作用。

lrl1mhuk

lrl1mhuk1#

管道流如下所示:
可读流-管道到-〉转换流-管道到-〉可写流
但是你必须创建一个干净的WritableStream,这就像一个缓冲区,用于向某个地方写入内容。
readableStream是从某个对象读取字节的流,在您的情况下,从文件读取照片是可读流,如下所示:

var http = require('http');
var fs = require('fs');

http.createServer(function(req, res) {
  // The filename is simple the local directory and tacks on the requested url
  var filename = __dirname+"/test.png";

  // This line opens the file as a readable stream
  var readStream = fs.createReadStream(filename);

  // This will wait until we know the readable stream is actually valid before piping
  readStream.on('open', function () {
    // This just pipes the read stream to the response object (which goes to the client)
    readStream.pipe(res);
  });

  // This catches any errors that happen while creating the readable stream (usually invalid names)
  readStream.on('error', function(err) {
    res.end(err);
  });
}).listen(8080);

这段代码将一个文件转换成一个读流,之后你必须创建一个写流,例如(在我的例子中是响应),但是你可以写另一个文件,例如通过管道传输到这个文件,如下所示:

var http = require('http');
var fs = require('fs');

http.createServer(function(req, res) {
  // The filename is simple the local directory and tacks on the requested url
  var filename = __dirname+"/test.png";
  var filename2 = __dirname+"/test2.png";

  // This line opens the file as a readable stream
  var readStream = fs.createReadStream(filename);
  var writeStream = fs.createWriteStream(filename2);
  // This will wait until we know the readable stream is actually valid before piping
  readStream.on('open', function () {
    // This just pipes the read stream to the write stream (duplicate the file)
    readStream.pipe(writeStream);
  });

  // This catches any errors that happen while creating the readable stream (usually invalid names)
  readStream.on('error', function(err) {
    res.end(err);
  });
  res.end("it's all");
}).listen(8080);

相关问题