nodejs 轻量级http服务器
代码:
javascript
var http = require('http');
var url = require('url');
var fs = require('fs'); //涉及文件读取
http.createServer(function (req, res, next) {
var pathname = url.parse(req.url).pathname;
///结尾的请求,自动添加上”index.html
if (pathname.slice(-1) === "/") {
pathname = pathname + 'index.html';
}
var path = __dirname + pathname;
var exists = fs.existsSync(path)
if (exists) {
var stat = fs.statSync(path);
if (stat.isFile()) {
fs.readFile(path, function (err, data) {
res.write(data);
res.end();
});
} else {
//不是文件一律输出403
res.writeHead(403);
res.end('403 This path cannot be accessed')
}
} else {
res.writeHead(404);
res.end('404 not found.')
}
}).listen(3000, function () {
console.log('listen http://localhost:3000')
});
var http = require('http');
var url = require('url');
var fs = require('fs'); //涉及文件读取
http.createServer(function (req, res, next) {
var pathname = url.parse(req.url).pathname;
///结尾的请求,自动添加上”index.html
if (pathname.slice(-1) === "/") {
pathname = pathname + 'index.html';
}
var path = __dirname + pathname;
var exists = fs.existsSync(path)
if (exists) {
var stat = fs.statSync(path);
if (stat.isFile()) {
fs.readFile(path, function (err, data) {
res.write(data);
res.end();
});
} else {
//不是文件一律输出403
res.writeHead(403);
res.end('403 This path cannot be accessed')
}
} else {
res.writeHead(404);
res.end('404 not found.')
}
}).listen(3000, function () {
console.log('listen http://localhost:3000')
});