node.js编写代码实现动态处理静态资源请求
时间: 2023-11-07 17:58:36 浏览: 75
可以使用Node.js的内置模块`http`和`fs`,结合`url`模块来实现动态处理静态资源请求。具体步骤如下:
1. 引入相应模块
```
const http = require('http');
const fs = require('fs');
const url = require('url');
```
2. 创建服务器
```
http.createServer((req, res) => {
const pathName = url.parse(req.url).pathname;
const filePath = `.${pathName}`;
fs.readFile(filePath, (err, data) => {
if (err) {
res.writeHead(404, {'Content-Type': 'text/html'});
res.write('<h1>404 Not Found</h1>');
res.end();
} else {
res.writeHead(200, {'Content-Type': 'text/html'});
res.write(data);
res.end();
}
});
}).listen(3000, () => {
console.log('Server running at http://localhost:3000/');
});
```
在上述代码中,首先通过`url.parse`方法获取请求的路径,然后通过`fs.readFile`方法读取该路径所对应的文件,如果文件不存在则返回404 Not Found的错误信息,否则返回文件内容。最后启动服务器并监听端口。
需要注意的是,上述代码只是一个简单的演示,没有考虑到并发请求、文件大小等问题,实际应用中还需要对代码进行优化和安全性处理。