How to Run Node scripts from the Command Line
Table of Contents
The command line is a powerful tool for developers and power users alike.
Being able to run commands directly from the command line as opposed to using a GUI is almost like a superpower.
You can use the command line to do anything you can do in a GUI, if the know the right command.
With that being said, you can run JavaScript through Node directly from the command line.
In this post, we'll learn how you can run Node scripts from the command line.
How to run Node scripts from the command line
To begin, let's start off with our example script:
JAVASCRIPTconst string = "123";
console.log(string);
Of course, if we ran this in the browser, we would get:
BASH123
However, since we want to run it in Node, let's save this as a file called script.js
.
Once we did that, open your command line and make sure you're in the same folder as the script.
Assuming you have Node installed, this is how you can run your script:
BASHnode script.js
BASH123
You simply need to use the node
command and pass it the path to the file you want to run.
How to re-run a Node app after changes are made
Now, if you want to keep running this file every time it changes, you can use a module called nodemon
for this exact scenario.
Install it locally:
BASHnpm install -g nodemon
Once you've done that, you can instead call nodemon
instead of node
:
BASHnodemon script.js
Conclusion
In this post, we learned how to run Node scripts from the command line.
Simply use the node
command to run a script or nodemon
to watch for changes and re-run it.
Thanks for reading!
- Getting Started with TypeScript
- How to Install Node on Windows, macOS and Linux
- Git Tutorial: Learn how to use Version Control
- How to Serve Static Files with Nginx and Docker
- How to deploy a MySQL Server using Docker
- How to deploy a Node app using Docker
- How to Scrape the Web using Node.js and Puppeteer
- Getting Started with Handlebars.js
- Getting Started with Moment.js
- Using Push.js to Display Web Browser Notifications
- Using Axios to Pull Data from a REST API
- How To Create a Modal Popup Box with CSS and JavaScript