【问题标题】:Proper way to pipe buffers in Node JS在 Node JS 中管道缓冲区的正确方法
【发布时间】:2015-01-14 00:59:34
【问题描述】:

看看:

var Client = require('ftp');
var fs = require('fs');

var c = new Client();
c.on('ready', function() {
  c.get('foo.txt', function(err, stream) {
    if (err) throw err;
    stream.once('close', function() { c.end(); });
    stream.pipe(fs.createWriteStream('foo.local-copy.txt'));
  });
});
// connect to localhost:21 as anonymous
c.connect();

这段代码来自https://www.npmjs.org/package/ftp。基本上,它打开一个读取流并将其通过管道传输到一个写入流中。最后它从源关闭连接。

管道流(源)关闭后,管道方法是否关闭目标流?我在 API 文档中找不到它。

我做了一些测试,我可以从女巫那里得出结论,但我不确定。

【问题讨论】:

    标签: node.js stream filesystems pipe fs


    【解决方案1】:

    当源发出end 事件时,目标流将关闭。这记录在Stream.pipe:

    默认情况下,当源流在目标端调用 end() 发出 end,因此目的地不再可写。

    这允许以下形式的调用:

    var http = require('http'),
      fs = require('fs');
    
    http.createServer(function (req, res) {
      fs.createReadStream('path/to/file').pipe(res);
    }).listen(3000);
    

    如果没有在 response 对象上调用 end,则请求将超时。

    这会使请求超时:

      fs.createReadStream('path/to/file').pipe(res, {end: false});
    

    【讨论】:

      猜你喜欢
      • 2021-10-27
      • 1970-01-01
      • 2017-07-12
      • 2019-12-08
      • 2020-09-05
      • 1970-01-01
      • 2018-01-18
      • 2018-09-18
      相关资源
      最近更新 更多