有意思,实现文件访问了
const http = require('http');
const fs = require('fs');
const path = require('path');
第一个http服务,第二个fs文件操作,第三个路径相关
const server = http.createServer((req, res) => {
});
在回调函数里面写功能 首先定义路径
let url = new URL(req.url, `http://${req.headers.host}`);
let pathname = url.pathname;
let filePath = path.join(__dirname, pathname);
//可以加个log看一下路径是否正确,这会在服务器运行,路径访问时打印
// console.log('Request for:' , filePath);
fs.readFile(filePath, (err, data) => {
if (err) {
res.writeHead(404, {'Content-Type': 'text/plain'});
res.end('Not found');
return;
} else {
// 根据文件扩展名设置Content-Type
// const ext = path.extname(filePath).toLowerCase();
//const mimeTypes = {
//'.html': 'text/html',
//'.js': 'application/javascript',
//'.css': 'text/css',
// 其他文件类型...
//现代浏览器的资源嗅探已经足够先进,因此对文件扩展名设置Content-Type并不是必要的
//};
// const contentType = mimeTypes[ext] || 'application/octet-stream';
// res.writeHead(200, {'Content-Type': contentType});
res.end(data);
}
})
server.listen(3000, () => {
console.log('Server running at http://localhost:3000/');
});
const server = http.createServer((req, res) => {
// 使用req.url和req.headers.host来创建完整的URL对象
let url = new URL(req.url, `http://${req.headers.host}`);
let pathname = url.pathname;
// 构建文件系统路径
let filePath = path.join(__dirname, pathname);
console.log('Request for:', filePath);
fs.readFile(filePath, (err, data) => {
if (err) {
res.writeHead(404, {'Content-Type': 'text/plain'});
res.end('Not found');
return;
} else {
// // 根据文件扩展名设置Content-Type
// const ext = path.extname(filePath).toLowerCase();
// const mimeTypes = {
// '.html': 'text/html',
// '.js': 'application/javascript',
// '.css': 'text/css',
// // 其他文件类型...
// 现代浏览器的资源嗅探已经足够先进,因此对文件扩展名设置Content-Type并不是必要的
// };
// const contentType = mimeTypes[ext] || 'application/octet-stream';
// res.writeHead(200, {'Content-Type': contentType});
res.end(data);
}
});
});
server.listen(3000, () => {
console.log('Server running at http://localhost:3000/');
});