写了一个简单的静态资源服务器,如果文件不存在或者路径是一个目录,则返回错误信息。这里有两个特点:
- 使用
async-to-js
进行异常处理; - 使用
stream
,通过pipe
方法将 Readable 写入到 Writable ,避免Readfile
方法一次性将整个文件加载到内存中;
后期需要在响应头中加上 Content-Type
。
const http = require("http");
const path = require("path");
const fs = require("fs");
const util = require("util");
const stats = util.promisify(fs.stat);
const to = p => p
.then(res => [res, null])
.catch(err => [null, err])
const getFileByUrl = async (requestUrl) => {
const filePath = path.resolve(__dirname, requestUrl.replace(/^\/(.*)$/, '$1'));
const [fileStats, err] = await to(stats(filePath));
if (err) {
return Promise.reject("File doesn\'t exist!");
}
if (fileStats.isDirectory()) {
return Promise.reject("Path doesn\'t appear to be a file!");
}
return fs.createReadStream(filePath);
}
http.createServer(async (req, res) => {
const [readable, err] = await to(getFileByUrl(req.url));
if (readable) {
readable.pipe(res);
} else {
res.end(JSON.stringify(err));
}
}).listen(3000);