问题描述
我试图在 nodejs 中创建一个静态文件服务器,更多的是作为理解 node 的练习,而不是作为一个完美的服务器.我非常了解 Connect 和 node-static 等项目,并且完全打算将这些库用于更多的生产就绪代码,但我也喜欢了解我正在使用的基础知识.考虑到这一点,我编写了一个小型 server.js:
I'm trying to create a static file server in nodejs more as an exercise to understand node than as a perfect server. I'm well aware of projects like Connect and node-static and fully intend to use those libraries for more production-ready code, but I also like to understand the basics of what I'm working with. With that in mind, I've coded up a small server.js:
var http = require('http'),
url = require('url'),
path = require('path'),
fs = require('fs');
var mimeTypes = {
"html": "text/html",
"jpeg": "image/jpeg",
"jpg": "image/jpeg",
"png": "image/png",
"js": "text/javascript",
"css": "text/css"};
http.createServer(function(req, res) {
var uri = url.parse(req.url).pathname;
var filename = path.join(process.cwd(), uri);
path.exists(filename, function(exists) {
if(!exists) {
console.log("not exists: " + filename);
res.writeHead(200, {'Content-Type': 'text/plain'});
res.write('404 Not Found
');
res.end();
}
var mimeType = mimeTypes[path.extname(filename).split(".")[1]];
res.writeHead(200, mimeType);
var fileStream = fs.createReadStream(filename);
fileStream.pipe(res);
}); //end path.exists
}).listen(1337);
我的问题是双重的
这是在节点中创建和流式传输基本 html 等的正确"方式还是有更好/更优雅/更健壮的方法?
Is this the "right" way to go about creating and streaming basic html etc in node or is there a better/more elegant/more robust method ?
node 中的 .pipe() 是否基本上只是在执行以下操作?
Is the .pipe() in node basically just doing the following?
.
var fileStream = fs.createReadStream(filename);
fileStream.on('data', function (data) {
res.write(data);
});
fileStream.on('end', function() {
res.end();
});
谢谢大家!
推荐答案
你的基本服务器看起来不错,除了:
Your basic server looks good, except:
缺少
return
语句.res.write('404 Not Found '); res.end(); return; // <- Don't forget to return here !!
还有:
res.writeHead(200, mimeType);
应该是:
res.writeHead(200, {'Content-Type':mimeType});
是的
pipe()
基本上就是这样做的,它还暂停/恢复源流(以防接收器速度较慢).下面是pipe()
函数的源代码:https:///github.com/joyent/node/blob/master/lib/stream.jsYes
pipe()
does basically that, it also pauses/resumes the source stream (in case the receiver is slower).Here is the source code of thepipe()
function: https://github.com/joyent/node/blob/master/lib/stream.js这篇关于NodeJS 中的基本静态文件服务器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!