我见过很多人动态地在他们的路线/ 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...
答案 0 :(得分:3)
似乎在生产中,当前目录未设置为“routes”目录的父目录。你是如何在生产中推出你的应用程序的?您从
获得了什么输出console.log(process.cwd());
答案 1 :(得分:3)
正如Mark Bessey在他的回答中所说,您正在解析当前目录中的routes
目录 - 而不是相对于主脚本所在的位置。您应该使用__dirname
。来自the docs:
当前正在执行的脚本所在的目录的名称。
fs.readdirSync(path.join(__dirname, "routes"))
此外,您无需通过'utf8'
。另外,在代码中使用任何 Sync
函数时要非常小心 - 通常,在服务器开始接受请求之前,它在顶级作用域中是可以的,所以在这种情况下应该没问题