【发布时间】:2015-11-26 03:05:54
【问题描述】:
我创建了一个BasicWebServer.js 文件,该文件位于portfolio-website 文件夹中,该文件夹包含以下文件:index.htm、BasicWebServer.js、css/style.css。
我在 BasicWebServer.js 文件中的代码如下:
var http = require('http'),
fs = require('fs'),
path = require('path'),
host = '127.0.0.1',
port = '9000';
var mimes = {
".htm" : "text/html",
".css" : "text/css",
".js" : "text/javascript",
".gif" : "image/gif",
".jpg" : "image/jpeg",
".png" : "image/png"
}
var server = http.createServer(function(req, res){
var filepath = (req.url === '/') ? ('./index.htm') : ('.' + req.url);
var contentType = mimes[path.extname(filepath)];
// Check to see if the file exists
fs.exists(filepath, function(file_exists){
if(file_exists){
// Read and Serve
fs.readFile(filepath, function(error, content){
if(error){
res.writeHead(500);
res.end();
} else{
res.writeHead(200, { 'Content-Type' : contentType});
res.end(content, 'utf-8');
}
})
} else {
res.writeHead(404);
res.end("Sorry we could not find the file you requested!");
}
})
res.writeHead(200, {'content-type' : 'text/html'});
res.end('<h1>Hello World!</h1>');
}).listen(port, host, function(){
console.log('Server Running on http://' + host + ':' + port);
});
更新 1 第 1 部分)
我删除了这两行:
res.writeHead(200, {'content-type' : 'text/html'});
res.end('<h1>Hello World!</h1>');
当我刷新页面时,我得到:
Sorry we could not find the file you requested!
第 2 部分) 我也试过这样做:
var http = require('http'),
fs = require('fs'),
path = require('path'),
host = '127.0.0.1',
port = '9000';
var mimes = {
".htm" : "text/html",
".css" : "text/css",
".js" : "text/javascript",
".gif" : "image/gif",
".jpg" : "image/jpeg",
".png" : "image/png"
}
var server = http.createServer(function (req, res) {
var filepath = (req.url === '/') ? ('./index.htm') : ('.' + req.url);
var contentType = mimes[path.extname(filepath)];
// Check to see if the file exists
fs.exists(filepath, function(file_exists){
// if(file_exists){
// // Read and Serve
// fs.readFile(filepath, function(error, content){
// if(error){
// res.writeHead(500);
// res.end();
// } else{
// res.writeHead(200, { 'Content-Type' : contentType});
// res.end(content, 'utf-8');
// }
// })
res.writeHead(200, {'Content-Type' : contentType});
var streamFile = fs.createReadStream(filepath).pipe(res);
streamFile.on('error', function() {
res.writeHead(500);
res.end();
})
} else {
res.writeHead(404);
res.end("Sorry we could not find the file you requested!");
}
})
}).listen(port, host, function(){
console.log('Server Running on http://' + host + ':' + port);
});
这会产生以下错误:
SyntaxError: Unexpected token else
at exports.runInThisContext (vm.js:73:16)
at Module._compile (module.js:443:25)
at Object.Module._extensions..js (module.js:478:10)
at Module.load (module.js:355:32)
at Function.Module._load (module.js:310:12)
at Function.Module.runMain (module.js:501:10)
at startup (node.js:129:16)
at node.js:814:3
【问题讨论】:
-
FWIW(在其他现有解决方案中)您可以使用
fs.createReadStream,然后使用pipe。
标签: javascript node.js server-side serverside-javascript