How to execute a JavaScript file in Node.js?

Sometimes, we want to execute a JavaScript file in Node.js.

In this article, we’ll look at how to execute a JavaScript file in Node.js.

How to execute a JavaScript file in Node.js?

To execute a JavaScript file in Node.js, we can run the node command with the path of the JavaScript file we want to run.

For instance, we run:

node C:UsersJohnDownloadsNodeJSworkinghello_world.js

to run the C:UsersJohnDownloadsNodeJSworkinghello_world.js file with the node command.

We can also run:

cd C:UsersJohnDownloadsNodeJSworking
node hello_world.js

to change the current working directory to the folder where the file is with cd.

Then we run hello_world.js in the current working directory with node.

Conclusion

To execute a JavaScript file in Node.js, we can run the node command with the path of the JavaScript file we want to run.