我对 module.exports 的性质有疑问 我正在尝试使用 postgres、express 和 node 构建一个简单的待办事项应用程序。
这是我的 index.js
const express = require("express");
const cors = require("cors");
const pool = require("./db");
const app = express();
const PORT = 5000;
app.use(cors());
app.use(express.json());
console.log("2");
app.get("/todos", async (req, res) => {
try {
const result = await pool.query("SELECT * FROM todo");
res.json(result.rows);
} catch (err) {
console.log(err);
}
});
这是我的 db.js
const fs = require("fs").promises;
const path = require("path");
const pgtools = require("pgtools");
const { Pool } = require("pg");
const dB = "perntodo";
const config = {
user: "postgres",
password: "my_pass",
port: 5432,
host: "localhost",
};
const createDB = async () => {
try {
await pgtools.createdb(config, dB);
console.log(`database ${dB} created`);
} catch (err) {
console.log(err);
}
};
createDB()
.then(async () => {
const pool = new Pool({
...config,
database: dB,
});
const schemaPath = path.join(__dirname, "database.sql");
const schema = await fs.readFile(schemaPath, "utf8");
await pool.query(schema);
return pool;
})
.then((pool) => {
console.log("1");
module.exports = pool;
})
.catch((err) => console.log(err));
database.sql 只是一个简单的建表查询。
我面临的这个问题是,module.exports 甚至发生在 pool 的值成为由 new Pool 实例化的对象之前,因此我从 index.js 收到以下错误消息
TypeError: pool.query is not a function
我在我的代码中放置了 console.logs,似乎承诺链有问题,因为 2 在 1 之前执行。
我的承诺链到底有什么错误?
这就是我认为的db.js的控制流程, 首先,调用 createDB() 函数创建 perntodo 数据库(如果它不存在)。创建数据库后,将执行第一个 .then() 块,它创建一个新池并使用 pool.query() 将 SQL 模式文件加载到数据库中。 Pool 对象被分配给在块外声明的池变量。
最后,执行第二个 .then() 块,使用 module.exports 将池对象设置为当前文件的导出模块。这确保池对象可用于需要此模块的应用程序的其他部分。