原先的模版
1 2 3 4 5 6 7 8 9 l=[]; l.push('<body > '); if($.a>$.b){ l.push('a 大於 b'); }else{ l.push('a 小於 b'); } l.push('</body > '); return l.join('');
原先的 fs.readFile 解釋模版方法
1 2 3 4 5 6 7 8 var http=require ('http' ), fs=require ('fs' ); http.createServer(function (request,response,l ) { fs.readFile('./temp.js' ,'utf8' ,function (err,temp ) { var data={a :1 ,b :3 }; response.end(Function ('$,l' ,temp)(data)); }); }).listen(8888 );
經由新 fs.createReadStream 解釋模版方法
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 var util = require ('util' ), stream = require ('stream' ), http = require ('http' ), fs = require ('fs' ); 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; }; http.createServer(function (request, response ) { var temp = fs.createReadStream("temp.js" ); temp.setEncoding("utf8" ); temp.pipe(new CompileStream({ a: 1 , b: 2 })).pipe(response); }).listen(8888 );
移除 _parse 的 fs.createReadStream 的代碼
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 var CompileStream = function (data ) { this .readable = true ; this .writable = true ; this .setDatas = data; } util.inherits(CompileStream, stream); CompileStream.prototype.write = function ( ) { var data = Array .prototype.slice.apply(arguments )[0 ]; data = data ? data.toString() : "" ; data = Function ('$,l' , data)(this .setDatas); this .emit('data' , data); }; CompileStream.prototype.end = function ( ) { this .emit("end" ); }; CompileStream.prototype.setData = function (name, value ) { this .setDatas[name] = value; };
關於將 html 編譯成 js 代碼 (不完全記錄)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 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);