用RESTIFY服务静态文件

我正在学习使用Node.js. 目前,我有一个文件夹结构,如下所示:

index.html server.js client index.html subs index.html page.html res css style.css img profile.png js page.js jquery.min.js 

server.js是我的networking服务器代码。 我使用node server.js从命令行运行。 该文件的内容是:

 var restify = require('restify'); var server = restify.createServer({ name: 'Test App', version: '1.0.0' }); server.use(restify.acceptParser(server.acceptable)); server.use(restify.queryParser()); server.use(restify.bodyParser()); server.get('/echo/:name', function (req, res, next) { res.send(req.params); return next(); }); server.listen(2000, function () { console.log('%s running on %s', server.name, server.url); }); 

正如你所看到的,这个服务器依赖于RESTIFY。 我被告知我必须使用RESTIFY。 但是,我不知道如何提供静态文件。 例如,如何在我的应用程序中服务* .html,* .css,* .png和* .js文件?

谢谢!

从文档 :

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

但是这将search./public/docs/public/目录中的文件。
我更喜欢在这里使用__dirname键:

 server.get(/\/public\/?.*/, restify.serveStatic({ directory: __dirname })); 

现在我们将所有/public/.*url映射到./public/目录。

根据我目前的版本(v5.2.0)

serveStatic已经被移入plugins ,所以代码将是这样的

 server.get( /\/(.*)?.*/, restify.plugins.serveStatic({ directory: './static', }) ) 

上面的语法将静态文件夹中的static文件。 所以你可以得到像http://yoursite.com/awesome-photo.jpg这样的静态文件

出于某种原因,如果你想在特定的path下提供静态文件,例如http://yoursite.com/assets/awesome-photo.jpg

代码应该重构成这个

 server.get( /\/assets\/(.*)?.*/, restify.plugins.serveStatic({ directory: `${app_root}/static`, appendRequestPath: false }) ) 

上面的appendRequestPath: false选项意味着我们不包括assetspath到文件名中

我刚才遇到这个问题,所以虽然这可能对你没有帮助,但可以帮助其他有困难的人。

当你声明Restify为const restify = require('restify'); ,serveStatic方法将在插件对象,所以使用restify.serveStatic将悄然失败。 访问该方法的正确方法是restify.plugins.serveStatic

您可以在这里find更新文档: http : //restify.com/docs/plugins-api/#serve-static

 server.get('/', function(req, res, next) { fs.readFile(__dirname + '/index.html', function (err, data) { if (err) { next(err); return; } res.setHeader('Content-Type', 'text/html'); res.writeHead(200); res.end(data); next(); }); }); 

试试这个:这里的view是一个静态的资源目录名

 server.get('/\/.*/', restify.plugins.serveStatic({ directory: __dirname + "/view/", default: './home.html' }) );