为了在不使用 express 或其他已经过测试和首选方式的情况下提供您的 bundle.js 文件和其他文件,您可以提供您喜欢的任何文件(请参阅“routeToFile”函数)。
//Return the file path you want to serve to that request url
const routeToFile = ({url}) => {
if(url === '/'){
return './index.html';
}
return `.${url}`;
}
使用“mimeTypes”数组,您只需检查文件扩展名 (mimeTypes[fileExtension]) 即可猜出正确的 mime 类型。
//File mime types for content type response
const mimeTypes = {
'.html': 'text/html',
'.js': 'text/javascript',
'.css': 'text/css',
'.json': 'application/json',
'.png': 'image/png',
'.jpg': 'image/jpg'
};
如果出现错误,例如文件不存在,只需发送错误代码,或者您也喜欢的页面(参见“onError”函数)
//If the file is missing or there is an error
const onError = (error, response) => {
if(error.code == 'ENOENT') {
response.writeHead(404);
}
else {
response.writeHead(500);
console.error(error);
}
response.end();
}
最后,运行所有这些的主要函数是:
//Create the http server
http.createServer((req, res) => {
const filePath = routeToFile(req)
const fileExtension = String(path.extname(filePath)).toLowerCase();
const contentType = mimeTypes[fileExtension] || 'application/octet-stream';
fs.readFile(filePath, function(error, content) {
if (error) {
return onError(error, res)
}
else {
res.writeHead(200, { 'Content-Type': contentType });
res.end(content, 'utf-8');
}
});
}).listen(PORT, () =>{
console.log(`server start at port ${PORT}`);
});
不要忘记要求,否则它将无法运行:D
const http = require('http');
const fs = require('fs');
const path = require('path');
const PORT = 3012