Чтобы обслужить ваш файл bundle.js и другие файлы без использования Express или другого уже проверенного и предпочтительного способа, вы можете обслужить любой файл (см. Функцию «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]).
//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