2012-05-05 73 views
1

我已经看到了很多人的dynaimcally生成它们在thier路线的所有路由/ index.js像这样:动态生成快递航线的生产环境无法

require("fs").readdirSync("./routes", 'utf8').forEach(function(file) { 
    if (file != 'index.js' && file != '.DS_Store') { 
     require("./"+file); 
    } 
}); 

这正常发展,但不是在生产。如果我删除这个并手动添加路线,它工作正常。有任何想法吗?

这里是我的错误,如果你认为这将有助于:

node.js:134 

throw e; // process.nextTick error, or 'error' event on first tick 

Error: ENOENT, No such file or directory './routes' 
    at Object.readdirSync (fs.js:376:18) 
    at Object.<anonymous> (/app/routes/index.js:4:15) 
    at Module._compile (module.js:402:26) 
    at Object..js (module.js:408:10) 
    at Module.load (module.js:334:31) 
    at Function._load (module.js:293:12) 
    at require (module.js:346:19) 
    at Object.<anonymous> (/app/server.js:50:14) 
    at Module._compile (module.js:402:26) 
    at Object..js (module.js:408:10) 
Process died with exit code 1. Restarting... 

回答

3

得到什么输出正如马克·贝西说,在他的回答,你是从解决当前目录的routes目录 - 不是相对于主脚本住在哪里。您应该使用__dirname。从the docs

与当前执行的脚本所在目录的名称

fs.readdirSync(path.join(__dirname, "routes")) 

而且,你不需要通过'utf8'。另外,请谨慎使用代码中的任意Sync函数 - 通常,在服务器开始接受请求之前,在顶层范围内可以,因此在这种情况下应该可以。

+0

为什么使用'path.join(__ dirname,“routes”)'而不是'__dirname'?路径从哪里来? – Pardoner

+0

你可以使用'__dirname +“/ routes”'''path.join'是平台独立的。 'path'来自'var path = require('path')'。请参见[node.js路径模块文档](http://nodejs.org/api/path.html)。 –

3

这很可能是在生产,当前目录不获取设置为你的“路线”目录的父。你如何在生产中启动你的应用程序?你从

console.log(process.cwd());