Return 从模块输出到 express 路由的 nodejs 流

Return nodejs stream output from module to express route

我刚刚开始 nodejs/express 开发并且在数据流方面遇到了困难。这是场景:

我想读取文件、处理内容(全部在一个模块中)和 return 处理后的输出以便显示。我怎样才能做到这一点?

这是一些代码:

app.js

var express = require('express');
var parseFile = require('./parse_file.js');

app.get('/', function(req, res, next){
  parsedExport = parseFile(__dirname+'/somefile.txt');
  res.send(parsedExport);
});

server = http.createServer(app);
server.listen(8080);

parse_file.js

var fs = require('fs');

var ParseFile = function(filename) {
    var parsedExport = [];
    rs = fs.createReadStream(filename);
    parser = function(chunk) {
        parsedChunk = // Do some parsing here...
        parsedExport.push(parsedChunk);        
    };
    rs.pipe(parser);
    return parsedExport;
};

module.exports = ParseFile;

任何人都可以向我展示一个如何实现此目标的工作示例?或者指出我正确的方向?

您可以使用transform stream:

app.js:

var express = require('express');
var parseFile = require('./parse_file.js');

var app = express();

app.get('/', function(req, res, next){
  parseFile(__dirname+'/somefile.txt').pipe(res);
});

server = http.createServer(app);
server.listen(8080);

parse_file.js:

var fs = require('fs');

var ParseFile = function(filename) {

  var ts = require('stream').Transform();

  ts._transform = function (chunk, enc, next) {
    parsedChunk = '<chunk>' + chunk + '</chunk>'; // Do some parsing here...
    this.push(parsedChunk);
    next();
  };

  return fs.createReadStream(filename).pipe(ts);

};   

module.exports = ParseFile;