I´m just starting nodejs/express development and stumbling over streams. Here is the scenario:
I want to read a file, process the content (all in a module) and return the processed output so it can be displayed. How can I achieve this?
Here is some 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 = // Do some parsing here...
parsedExport.push(parsedChunk);
};
rs.pipe(parser);
return parsedExport;
};
module.exports = ParseFile;
Anyone can show me a working example how to achieve this? Or point me in the right direction?
You can use 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;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With