1

I am trying to get my Sequelize migration scripts to run automatically when my node application starts. I have manually tested the migration scripts to make sure they are running correctly, by running db:migrate command.

Now, I have added this file to run the migration scripts:

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
};

And in 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.');

When I start the app, it displays Migrating DB... and gets stuck there.

How can I resolve this?

Jay
  • 329
  • 1
  • 6
  • 22
  • You can add this in package.json like: start-and-migrate: "NODE_ENV=development npm run db:migrate and node index.js" – Dmytro Mysak May 08 '19 at 11:16
  • Did you ever end up resolving this? I'm running into a similar issue after my migrations have already run. The db:migrate command gets stuck on the "No migrations were executed, database schema was already up to date." message and never resolves anything. – developthewebz Oct 08 '19 at 02:06

1 Answers1

1

You can listen for the console message and kill the child process, like this:

// 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();
      }
    });

This will make sure that the child process is killed when you've already run your migrations.

Mino De Raj
  • 301
  • 2
  • 6
  • solution is from [link](https://stackoverflow.com/questions/58279065/running-sequelize-migration-and-node-server-in-same-command-wont-start-server-u). As i have less reputation, i'm not able to add a comment on other's reply. – Mino De Raj Oct 23 '19 at 07:10