加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
文件
该仓库未声明开源许可证文件(LICENSE),使用请关注具体项目描述及其代码上游依赖。
克隆/下载
nserver.js 3.36 KB
一键复制 编辑 原始数据 按行查看 历史
无鞘之刃 提交于 2017-04-04 22:57 . 完成
const http = require('http');
const url = require('url');
const fs = require('fs');
const util = require('util');
const qs = require('querystring');
const httpDir = process.argv[2];
const httpPort = process.argv[3];
const IP = "127.0.0.1"
const mimetype = {
'txt': 'text/plain',
'htm': 'text/html',
'html': 'text/html',
'css': 'text/css',
'xml': 'application/xml',
'json': 'application/json',
'js': 'application/javascript',
'jpg': 'image/jpeg',
'jpeg': 'image/jpeg',
'gif': 'image/gif',
'png': 'image/png',
'svg': 'image/svg+xml'
}
const defaultPage = [
'index.html'
]
const TIP = `
_ __ ___ ___ _ ____ _____ _ __
| '_ \\/ __|/ _ \\ '__\\ \\ / / _ \\ '__|
| | | \\__ \\ __/ | \\ V / __/ |
|_| |_|___/\\___|_| \\_/ \\___|_|
Server running at ${IP}:${httpPort}/
`
console.log(TIP);
const page_404 = function(req, res, path){
res.writeHead(404, {
'Content-Type': 'text/html'
});
res.write('<!doctype html>\n');
res.write('<title>404 Not Found</title>\n');
res.write('<h1>Not Found</h1>');
res.write(
'<p>The requested URL ' +
path +
' was not found on this server.</p>'
);
res.end();
}
const page_500 = function(req, res, error){
res.writeHead(500, {
'Content-Type': 'text/html'
});
res.write('<!doctype html>\n');
res.write('<title>Internal Server Error</title>\n');
res.write('<h1>Internal Server Error</h1>');
res.write('<pre>' + util.inspect(error) + '</pre>');
}
var writeOut = function (query, res, realPath) {
res.writeHead(200, {
'Content-Type': mimetype[realPath.split('.').pop()] || 'text/plain'
});
res.write(JSON.stringify(query));
res.end();
}
http.createServer(function (req, res) {
let urlSet = url.parse(req.url);
let pathname = urlSet.pathname.indexOf('.') != -1 ? urlSet.pathname : urlSet.pathname + defaultPage[0];
let realPath = httpDir + pathname;
console.log((new Date()) + " : " + realPath);
fs.exists(realPath, function(exists){
if(!exists){
if ( urlSet.pathname === "/generate" && req.method.toUpperCase() == 'POST') {
var postData = "";
/**
* 因为post方式的数据不太一样可能很庞大复杂,
* 所以要添加监听来获取传递的数据
* 也可写作 req.on("data",function(data){});
*/
req.addListener("data", function (data) {
postData += data;
});
/**
* 这个是如果数据读取完毕就会执行的监听方法
*/
req.addListener("end", function () {
var query = qs.parse(postData);
fs.writeFile(query.output, query.html, function(err) {
if(err) {
return console.log(err);
}
console.log("The file was saved!");
});
writeOut(query, res, realPath);
});
} else {
return page_404(req, res, pathname);
}
} else {
let file = fs.createReadStream(realPath);
res.writeHead(200, {
'Content-Type': mimetype[realPath.split('.').pop()] || 'text/plain'
});
file.on('data', res.write.bind(res));
file.on('close', res.end.bind(res));
file.on('error', function(err){
return page_500(req, res, err);
});
}
});
}).listen(httpPort, IP);
Loading...
马建仓 AI 助手
尝试更多
代码解读
代码找茬
代码优化