node.js - Return nodejs stream output from module to express route -


i´m starting nodejs/express development , stumbling on streams. here scenario:

i want read file, process content (all in module) , return processed output can displayed. how can achieve this?

here code:

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 = // parsing here...         parsedexport.push(parsedchunk);             };     rs.pipe(parser);     return parsedexport; };  module.exports = parsefile; 

anyone can show me working example how achieve this? or point me in right direction?

you can use transform stream:

app.js:

var express = require('express'); var parsefile = require('./parse_file.js');  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>'; // parsing here...     this.push(parsedchunk);     next();   };    return fs.createreadstream(filename).pipe(ts);  };     module.exports = parsefile; 

Comments

Popular posts from this blog

java - pagination of xlsx file to XSSFworkbook using apache POI -

Unlimited choices in BASH case statement -

apache - How do I stop my index.php being run twice for every user -