我正在尝试让我的Sequelize迁移脚本在节点应用程序启动时自动运行。我已经通过运行db:migrate命令手动测试了迁移脚本,以确保它们正确运行。
现在,我已添加此文件来运行迁移脚本:
index.js
const {exec} = require('child_process');
const Sequelize = require('sequelize');
const config = require("config");
const sequelize = new Sequelize(config.get('postgres'));
async function start() {
await new Promise((resolve, reject) => {
const migrate = exec(
'npm run db:migrate',
{env: 'development'},
(err, stdout, stderr) => {
if (err) {
reject(err);
} else {
resolve();
}
}
);
// Forward stdout+stderr to this process
migrate.stdout.pipe(process.stdout);
migrate.stderr.pipe(process.stderr);
});
}
module.exports = {
start: start
};
在server.js中:
async function start(appStarted) {
logger.info('Initializing ...');
// execute pending migrations
logger.info('Migrating DB...');
await require('../migrations').start();
logger.info('DB Migration complete.');
当我启动该应用程序时,它会显示Migrating DB ...,并卡在其中。
我该如何解决?
答案 0 :(得分:1)
您可以侦听控制台消息并杀死子进程,如下所示:
// Listen for the console.log message and kill the process to proceed to the next step in the npm script
migrate.stdout.on('data', (data) => {
console.log(data);
if (data.indexOf('No migrations were executed, database schema was already up to date.') !== -1) {
migrate.kill();
}
});
这将确保已经运行迁移的子进程被杀死。