简体   繁体   English

NodeJS从缓冲区创建流

[英]NodeJS Create stream from buffer

I save my file to a buffer and cache the buffer for future use. 我将文件保存到缓冲区并缓存缓冲区以备将来使用。 Now I want to use the buffer to create a stream so that I can pipe it to the response again. 现在我想使用缓冲区来创建一个流,以便我可以再次将它传递给响应。 Is this possible? 这可能吗? and if it is then how? 如果是的话怎么样?

I found this most promising, thanks to felixge (node committer, esp stream module) https://github.com/felixge/node-combined-stream 感谢felixge(节点提交者,esp流模块) https://github.com/felixge/node-combined-stream ,我发现这是最有希望的。

Example of piping a file to buffer first then construct a stream and pipe to process std out, modified from the article 首先将文件管道缓冲然后构造一个流和管道来处理std的示例,从文章中修改

(you can pipe from file systems stream directly, here is for illustrate) (你可以直接从文件系统流管道,这里是为了说明)

Async loading buffer from file 从文件中异步加载缓冲区

var fs = require("fs");
var fileName = "image.jpg";

var CombinedStream = require('combined-stream');

var combinedStream = CombinedStream.create();

fs.exists(fileName, function(exists) {
  if (exists) {
    fs.stat(fileName, function(error, stats) {
      fs.open(fileName, "r", function(error, fd) {
        var buffer = new Buffer(stats.size);
        fs.read(fd, buffer, 0, buffer.length, null, function(error, bytesRead, buffer) {
             fs.close(fd);

           //even the file stream closed
           combinedStream.append(buffer);
           combinedStream.pipe(process.stdout);


        });
      });
    });
  }
});

Sync Loading buffer from file: 从文件同步加载缓冲区:

//get buffer
var buffer = readFileSync(fileName);
//or do it yourself
var stats = fs.statSync(fileName);
var buffer = new Buffer(stats.size);
var fd = fs.openSync(fileName,"r");
fs.readSync(fd,buffer,0,buffer.length,null);
fs.close(fd);

combinedStream.append(buffer);
combinedStream.pipe(process.stdout);

There's no native functionality in node for doing this. 这样做在节点中没有本机功能。 You might search around a bit to see if there are third-party libraries for it. 您可以搜索一下,看看是否有第三方库。 If there aren't, it's possible, if a bit tedious, to write your own module that will do it, since any class that implements all the methods and properties listed in the documentation for Stream and emits and responds to all the events listed in the documentation is , by definition, a Stream and can be used anywhere that node's built-in Stream s can. 如果没有,有可能,如果有点单调乏味,编写自己的模块来完成它,因为任何实现Stream文档中列出的所有方法和属性的类都会发出并响应所列出的所有事件文档顾名思义,一个Stream可以在任何地方使用该节点的内置Stream S能。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM