learning nodejs 1 - stream.pipe

2023-05-25,,

a simple http server using inner http module.
var http = require('http');
var fs = require('fs');

// 这是一个很有趣的包
require('colors'); var server = http.createServer(function(req, res) { if ('GET' == req.method && '/images' == req.url.substr(0, 7) && '.jpg' == req.url.substr(-4)) { console.log(req.url.red);
console.log((__dirname + req.url).red); fs.stat(__dirname + req.url, function(err, stat) { if (err || ! stat.isFile()) {
res.writeHead(404);
res.end('Not found');
return;
} serve(__dirname + req.url, 'image/jpg'); }); } else if ('GET' == req.method && '/' == req.url) { serve(__dirname + '/index.html', 'text/html'); } else { res.writeHead(404);
res.end('Not found');
} function serve(path, type) { console.log(path.yellow);
console.log(type.red); res.writeHead(200, {'Content-Type': type}); // 这个是亮点,流的管道方法,类似C++的 <<
fs.createReadStream(path).pipe(res);
} }).listen(3000);

learning nodejs 1 - stream.pipe的相关教程结束。

《learning nodejs 1 - stream.pipe.doc》

下载本文的Word格式文档,以方便收藏与打印。