返回nodejs流从模块输出到表达路由

时间:2016-02-08 18:23:18

标签: node.js express node-modules

我刚刚开始使用nodejs / express开发并在流上遇到困难。这是场景:

我想读取一个文件,处理内容(模块中的所有内容)并返回已处理的输出,以便显示它。我怎样才能做到这一点?

以下是一些代码:

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;

任何人都可以告诉我一个如何实现这个目标的工作示例?还是指出我正确的方向?

1 个答案:

答案 0 :(得分:4)

您可以使用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;