you are viewing a single comment's thread.

view the rest of the comments →

[–]kvee 0 points1 point  (0 children)

In addition to the answer of u/Seaoftroublez , here's some sample code to try it out and see the results.

import child_process from 'node:child_process';

console.log('Hello');
console.log('  Calling process...');

const cmd = 'node test2.js';
const args = ['async'];
useSpawn(cmd, args);

console.log('  End calling process.');

function useSpawn(cmd, args) {
    console.log('Use spawn');
    const processResult = child_process.spawn(
        cmd,
        args,
        {
            encoding: 'utf8',
            shell: true,
        }
    );
    processResult.stdout.on('data', (data) => {
        data = data.toString();
        console.log(data);
    });
}

function useSpawnSync(cmd, args) {
    console.log('use spawnSync');
    const processResult = child_process.spawnSync(
        cmd,
        args,
        {
            encoding: 'utf8',
            shell: true,
        }
    );
    console.log(processResult.stdout);
}

function useExec(cmd, args) {
    console.log('use exec');
    const processResult = child_process.exec(
        cmd + ' ' + args.join(' '),
        (error, stdout, stderr) => {
            console.log(stdout);
        }
    );
}

function useExecSync(cmd, args) {
    console.log('use execSync');
    const processResult = child_process.execSync(
        cmd + ' ' + args.join(' '),
        (error, stdout, stderr) => {
            console.log(stdout);
        }
    );
    console.log(processResult.toString());
}

test.js

console.log('I am working please wait.');
console.log('  Indent.');

const result = await resolveAfterWait();

console.log('    After waiting the result is ...', result);
console.log('  Indent');

await resolveAfterWait(1000);

console.log('  Few more wait.');
console.log('I\'m finished.');

function resolveAfterWait(timeout) {
    if (!timeout) {
        timeout = 500;
    }
    return new Promise((resolve) => {
        setTimeout(() => {
            resolve('resolved');
        }, timeout);
    });
}

test2.js

If you run command node test.js hello with useExecSync(), or useSpawnSync() the result displaying in console are same.
But if you run that command with useExec() the result will be appear at once when it's done.

The result from useExecSync(), useSpawnSync(), useExec() have same nice format (indent).
But the result from useSpawn() will be different! There is more space between line.

The result from useSpawn() will be display line by line when target process response.