代码拉取完成,页面将自动刷新
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);
此处可能存在不合适展示的内容,页面不予展示。您可通过相关编辑功能自查并修改。
如您确认内容无涉及 不当用语 / 纯广告导流 / 暴力 / 低俗色情 / 侵权 / 盗版 / 虚假 / 无价值内容或违法国家有关法律法规的内容,可点击提交进行申诉,我们将尽快为您处理。