1

I am working with Nodejs to create a tester module. So I need to use exec. This code work and is doing well:

const { exec } = require('child_process');

var nb_test = 1
var return_array = [nb_test];
var finished = 0;

var i = 0;

while (i < nb_test)
{
    var env = { "NB_MALLOC": i.toString()};
    console.log("coucou");
    console.log(i);
    exec("ls", { env }, function (error, stdout, stderr) {
        console.log(stdout);
        return_array[i] = { stdout, error, stderr };
        finished++;
    });
    i++;
}

but if I had this at the end, nothing is executed, the code never enter in the callback

 j = 0
while (j < nb_test){}

Any Idea why ?

0

2 Answers 2

1

Your callbacks never run because you never exit the current event loop. Async actions like your callback to exec are set aside to be executed after the current loop is finished. So node will execute all of the synchronous code in the entire script and only after this will it start processing callbacks. By placing an never-ending while loop in the script you make it impossible for Node to execute any callbacks. The while loop just spins and the callbacks patiently wait for it to finish. It's not clear why you want that last loop, but hopefully this will help you understand the behavior it is causing.

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks, that was that ! I thought Node would process the callback when the callback say he is finished, and so I could wait with the while loop !
0

You are not incrementing j inside the while loop. Therefore it will never exit.

Try adding j++; inside the while (j < nb_test){} braces.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.