Node.js +使用RESTIFY服务静态文件

use*_*401 9 node.js restify

我在站点中有.html,.js,.png,.css等文件的多级集合.看看我的网站hiearchy如下所示:

index.html
child1
  index.html
  page1.html
  page2.html
  ...
child2
  grandchild1
    index.html
  grandchild2
    index.html
  index.html
  page1.html
  page2.html
resources
  css
    myTheme.css
  img 
    logo.png
    profile.png
  js
    jquery.js
    ...
...
Run Code Online (Sandbox Code Playgroud)

我正在迁移它以在Node.js下运行.我被告知我必须使用RESTIFY.目前,我已经为我的服务器编写了以下内容:

var restify = require('restify');
var fs = require('fs');
var mime = require('mime');

var server = restify.createServer({
    name: 'Demo',
    version: '1.0.0'
});

server.use(restify.acceptParser(server.acceptable));
server.use(restify.queryParser());
server.use(restify.bodyParser());

server.get('/', loadStaticFile);

server.get('/echo/:name', function (req, res, next) {
    res.send(req.params);
    return next();
});

server.listen(2000, function () {
    console.log('Server Started');
});

function loadStaticFile(req, res, next) {
    var filePath = __dirname + getFileName(req);
    console.log("Returning " + filePath);

    fs.readFile(filePath, function(err, data) {
      if (err) {
        res.writeHead(500);
        res.end("");
        next(err);
        return;
      }

      res.contentType = mime.lookup(filename);
      res.writeHead(200);
      res.end(data);

      return next();
    });
}

function getFileName(req) {
    var filename = "";
    if (req.url.indexOf("/") == (req.url.length-1)) {
      filename = req.url + "index.html";
    } else {
      console.log("What Now?");
    }
    return filename;
}
Run Code Online (Sandbox Code Playgroud)

使用此代码,我可以成功加载index.html.但是,我的index.html文件引用了一些JavaScript,图像文件和样式表.我可以通过Fiddler看到这些文件正在被请求.但是,在我的node.js控制台窗口中,我从未看到"Returing [js | css | png filename]".就像我的node.js web服务器返回index.html而那就是它.

我究竟做错了什么?

小智 16

最新版本的restify内置了中间件serveStatic()中间件,可以为您完成此任务.

来自http://mcavage.me/node-restify/#Server-API

server.get(/\/docs\/public\/?.*/, restify.serveStatic({
  directory: './public'
}));
Run Code Online (Sandbox Code Playgroud)

更详细的例子:

http://mushfiq.me/2013/11/02/serving-static-files-using-restify/


lee*_*sei 5

您提供的任何文件是否包含相对路径(比方说../abc.js)?你必须用它path.resolve()来获得真正的路径fs.readFile().

无论如何,提供文件有很多陷阱:

  • 无效网址(400)
  • 找不到档案(404)
  • 转义序列(url编码)
  • fs.read() 将文件读入内存(@robertklep)
  • 等等

您可以使用现有的静态文件服务中间件.
我一直在使用Ecstatic,AFAIK它正确处理这些问题.

尝试

server.use(ecstatic({ root: __dirname + '/' }));
Run Code Online (Sandbox Code Playgroud)

如果失败,你可以参考这个堆栈的RESTify上连接/快递的顶部.