Skip to content

Instantly share code, notes, and snippets.

@zeuxisoo
Last active January 25, 2018 22:23
Show Gist options
  • Save zeuxisoo/5891800 to your computer and use it in GitHub Desktop.
Save zeuxisoo/5891800 to your computer and use it in GitHub Desktop.
Node.js custom PIPE object on createReadFileStream, createWriteFileStream
l = [];
l.push('<body>');
if ($.a > $.b) {
l.push('a > b');
}else{
l.push('a < b');
}
l.push('</body>');
return l.join('');
// Load Module
var util = require('util'),
stream = require('stream'),
http = require('http'),
fs = require('fs');
// Custom Stream
var CompileStream = function(data) {
this.readable = true;
this.writable = true;
this.setDatas = data;
}
util.inherits(CompileStream, stream);
CompileStream.prototype.write = function() {
this._parse.apply(this, arguments);
};
CompileStream.prototype.end = function() {
this.emit("end");
};
CompileStream.prototype._parse = function(data) {
data = data ? data.toString() : "";
data = Function('$,l', data)(this.setDatas);
this.emit('data', data);
};
CompileStream.prototype.setData = function(name, value) {
this.setDatas[name] = value;
};
// Make Web Server
http.createServer(function(request, response) {
var temp = fs.createReadStream("index-temp.js");
temp.setEncoding("utf8");
temp.pipe(new CompileStream({
a: 1,
b: 2
})).pipe(response);
}).listen(8888);
<p>{{ data }}</p>
var util = require('util'),
fs = require('fs'),
readStream = fs.createReadStream("n-test.html");
writeStream = fs.createWriteStream("test_c.txt");
var CompileStream = function() {
this.readable = true;
this.writable = true;
this.template = 'var template = ""; template = function(data) { return "##RESLT##" }';
};
util.inherits(CompileStream, require('stream'));
CompileStream.prototype.write = function() {
this._parse.apply(this, arguments);
};
CompileStream.prototype.end = function() {
this.emit("end");
};
CompileStream.prototype._parse = function(data) {
data = data ? data.toString() : "";
data = this.template.replace("##RESLT##", data);
this.emit("data", data);
}
readStream.pipe(new CompileStream()).pipe(writeStream);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment