nodemon 仅运行index.js 文件

问题描述 投票:0回答:2

在我的package.json文件中的scripts部分写着“start”:“nodemon index.js”,但是在我的项目中还有其他处理来自客户端的请求的文件,问题是只有那些路由在文件 workindex.js 中定义,这是为什么以及如何修复它?

我尝试将其他文件的代码放入一个函数中,然后导出这些函数并将它们导入到index.js文件中并调用它们。只有在那之后他们才开始工作,但在我看来这是非常错误的。我希望其他文件中的代码也能工作,但不将其导入到index.js文件中,因为在我看来,随着时间的推移,索引.js 文件会变得很大

import express from "express";
const app = express();
const PORT = 8000;
import authorization from "./authorization.js";
import { connect_to_mysql } from "./connect_to_mysql.js";
import registration from "./registration.js";


app.use("/public", express.static("public"));

(async function() {
        await connect_to_mysql();
        await authorization();
        await registration();
        await upload();
    
        app.listen(PORT, () => console.log("server started"));
})()

export { app, express };
node.js express nodemon
2个回答
0
投票

在您的

npm
脚本中,您仅运行
nodemon
index.js
文件,而不运行其他文件。最正确的方法是使用express
Router
类来生成其他端点(位于不同的文件中)或将函数从其他文件导出到
index.js
。该文件是唯一应该运行的文件,但您可以重构代码,以便将其分为不同的文件。


0
投票

使用 ESModule 时,您有一个起点(例如文件,

index.js
),并且您要使用的每个文件都必须导出某些内容并在某处导入。否则,该文件就不会被使用。

如果您不想过载

index.js
文件,只需在单独的文件中创建一个快速路由器即可:

import express from "express";

const router = express.Router();

router.post("/example", (req, res) => res.send());


export default router;

然后使用这个路由器(在

index.js
文件中):

import express from "express";

import router from "./routers/example";

const app = express();

app.use("/example", router);
© www.soinside.com 2019 - 2024. All rights reserved.