按照书上逐字打的,老是提示mime.lookup is not a function ,应该是有这个方法的吧?
下面是我的代码,求大神看看
var http = require('http');
var fs = require('fs');
var path = require('path');
var mime = require('mime');
var cache = {}; //cache是用来缓存文件中的数据的对象
//发送错误信息
function send404(res) {
res.writeHead(404,{'Content-Type':'text/plain'})
res.write('Error 404: resoure not found.');
res.end();
}
//发送文件
function sendFile(res, filePath, fileContents) {
res.writeHead(200, {
//path的basename方法获取路径的最后一部分,通过后缀名指定mime类型
'Content-Type': mime.lookup(path.basename(filePath))
});
res.end(fileContents);
}
//提供静态文件服务
function serveStatic(res, cache, absPath) {
if (cache[absPath]) {
sendFile(res, absPath, cache[absPath]);
} else {
//判断文件是否存在
fs.exists(absPath, function (exists) {
if (exists) {
//读取文件
fs.readFile(absPath, function (err, data) {
if (err) {
send404(res);
} else {
cache[absPath] = data;
sendFile(res, absPath, data);
}
});
} else {
send404(res);
}
});
}
}
//创建http服务器
var server = http.createServer(function (req, res) {
var filePath = false;
if (req.url == '/') {
filePath = 'public/index.html'; //返回静态的html文件
} else {
filePath = 'publc' + req.url; //将url转换为文件的相对路径
}
var absPath = './' + filePath;
serveStatic(res, cache, absPath);
});
//监听3000端口
server.listen(3000, function () {
console.log("Server start at port 3000");
});
去
npmjs
官网上看了下mime
的文档,mime
2.x.x
版本修改了函数名。截图如下:你去你的
package.json
中确认下你下载的mime
版本是不是2.x.x
,如果是,将你的方法名从lookup
修改成getType
再试试。