【求助】大家帮忙看下node代码,报错是什么问题?

按照书上逐字打的,老是提示mime.lookup is not a function ,应该是有这个方法的吧?
clipboard.png
下面是我的代码,求大神看看

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");
});
阅读 10.4k
4 个回答

npmjs官网上看了下mime文档mime 2.x.x 版本修改了函数名。截图如下:

clipboard.png

你去你的package.json中确认下你下载的mime版本是不是 2.x.x,如果是,将你的方法名从lookup修改成getType再试试。

lookup() renamed to getType()
试试mime.getType
实战这本书太老了。

mime.lookup 不是一个函数,mime 版本新的吧,更新日志上有这个
lookup() renamed to getType()
你可以试试getType

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题