JumpStart # 35– Prevent Visual Studio Node.js Console closing immediately after execution

In this JumpStart I am going to show how to prevent closing of Visual Studio’s Node.js console window  immediately after execution. When we create a blank Node.js Console application in Visual studio and run the application (either by clicking Start button or by pressing F5), app.js will execute and results will be printed, but the console will not wait by default for programmer to check results. This is the same default behavior as of C# console application, where we can by-pass it by using a simple Console.ReadLine() statement. But in Node.js project, we have other simple options which are discussed in this JumpStart.

Option 1

console.log('Hello world');

setTimeout(function () {
    process.exit();
}, 5000);

image

Using this approach, we can have enough time to view the results, ultimately console window is going to close after specified time interval.This approach doesn’t seem to be quite right way to solve the problem when user wants to re-run the code based on certain manual console inputs.

Option 2

console.log('Hello world');
process.wait(); // This is a defect

Simply inject a Defect (bug) at the last line of code. When Node encounters this line, there will be an unhandled error and the error will be printed in the console. Finally console waits for user to press any key.

image

Option 3 (Best Approach)

In this approach we need to install a NPM module “readline”, through which we can get user inputs from console window.

var read = require('readline');

var main = function () {
    console.log('Hello world');
    
    read.createInterface(process.stdin, process.stdout)
        .question("Press [e] to exit...", function (inputData) {
        if (inputData === "e")
            process.exit();
        else {
            main();
        }
    });
}

main();

Above code will run in a loop until user inputs “e” in the console window. This approach best suits if we want to run the program in a loop until user wants to exits the program.

image

Option 4

In this approach we are not going to run Node.js app from Visual Studio, instead we will run the app from Command prompt. To open command prompt from Visual Studio, please select below option.

image

And once Command prompt is up, we can execute app.js as shown below. Command Prompt will execute the code and then it stays there as it is even after code execution was done.

image

With above options, I am going to conclude this JumpStart. Stay tuned for more tips and tricks in Node.js. Happy Coding!!!

You may also like...