0

I am trying to build a main app that will run multiple microservices and for that i have npm install and build tasks, trying to put aysnc await for npm install tasks but it seems its not waiting for that task to complete and executing next function. is there way to wait for npm task to complete and then run next line of code or better thought to achieve this task.

index.js

const { exec } = require ('child_process');
const path = require('path');
const fs = require('fs');
const { executionAsyncResource } = require('async_hooks');

const appDirectory = __dirname;
const appDirs = fs.readdirSync(appDirectory);
let appPath;
(async () => {
console.log(appDirs);
    appDirs.forEach(appDir => {
        appPath = path.join(appDirectory, appDir);
        execute(appPath,appDir);
});

async function execute(appPath, appDir) {
    console.log("test", appDir);
    console.log(">>>>appPath", appDir);
    if(fs.lstatSync(appDir).isDirectory()) {
        appPath = path.join(appDirectory, appDir);
        await execInstall(appPath, appDir);
        console.log(`installing dependencies for ${appDir}`);
        await execBuild(appPath, appDir);
        console.log(`Buidstarted ${appDir}.........>>>>>>>`);
       await execRunApp(appPath);
        console.log(`${appDir} Build Completed>>>>>>`);
        console.log(`${appDir} App Started>>>>>>`);
    }
}

function execInstall(appPath, appDir) {
    const appInstallCmnd = "npm install";
    exec( appInstallCmnd, { cwd: appPath}, (error, stdout, stderr) => {
        if (error) {
            console.error(`Error installing dependencies for ${appDir}: ${error}`);
            return;
        }
    })
}
function execBuild(appPath, appDir) {
    const appbuildCmnd = "npm run build";
    exec(appbuildCmnd, { cwd: appPath}, (error, stdout, stderr) => {
        if(error) {
            console.error(`Error building>>>>>> ${appDir}: ${error} `);
        }
    })
}

function execRunApp(appPath, appDir) {
    const appRunLocal = "npm run serve-local";
    exec(appRunLocal, { cwd: appPath}, (error, stdout, stderr) => {
        if(error) {
            console.error(`Error Starting>>>>>> ${appDir}: ${error} `);
        }
    })
}
})();
Dave Newton
  • 158,873
  • 26
  • 254
  • 302
hussain
  • 6,587
  • 18
  • 79
  • 152
  • `await` only works with functions that return promises. None of your functions do. – Evert Mar 13 '23 at 16:51
  • `exec` is callback-based; you could promisify it *(or use `execSync`)*. That said not sure what this is really for--seems redundant. – Dave Newton Mar 13 '23 at 16:51
  • Your `exec` is using callbacks and `async....await` works with promises. You can try converting it to a promise. Have a look at this https://stackoverflow.com/a/56095793/4350275 – Prerak Sola Mar 13 '23 at 16:51

0 Answers0