在生产环境中dynamic生成快速路由失败

我见过很多人在他们的路线/ index.js中像这样dynamic地生成所有的路线:

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... 

正如Mark Bessey在他的回答中所说的那样,你正在解决当前目录中的routes目录 – 而不是你的主脚本所在的位置。 你应该使用__dirname 。 从文档 :

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

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

另外,你不需要传递'utf8' 。 另外,在代码中使用任何 Syncfunction时要非常小心 – 通常,在服务器开始接受请求之前,在顶层范围内是可以的,所以在这种情况下应该是可以的。

在生产中,似乎很可能当前目录没有被设置到“路由”目录的父目录。 你如何在生产中启动你的应用程序? 你从什么输出

 console.log(process.cwd());