Sometimes it’s the obvious things that trip you up….. I went through the process of installing and setting up Node js, created a Node JS web api and all was fine. When I came back to that project a few weeks later (Node.js is something I use intermittently) I couldn’t remember how to start the Node js server.
After Googling “how to run Node js file” I found loads of others asking the same question. So, whether you want to run your node.js file in Terminal, or in Command, or in the Visual Studio Code terminal here’s how you do it.
This post also tells you how to check if Node js is installed, and how to check the Node js version if it is.
Table of contents
Run a Node js file in terminal or command
- Open your Terminal / Command / Git Bash / Visual Studio Code Terminal window
- Change the folder location to your node project
- Type
node filename.js
- Press return
And that’s all there is to running a Node js file. In actual fact, you have started the Node js server. So if your file is called app.js you would type node app.js. If your file is called search.js then you’d type node search.js.
If you need a little more info than that to set up your project and run the Node js file, then check out this Node JS getting started guide. However, this does still presume that you already have Node installed…..
How to check if Node js is installed and check Node js version
Yep, I have had to do this on more than one occasion too. In order to check if you have Node js installed, or how to check your Node js version, follow these steps:
- Open your command line tool (as above, Terminal, Command, Git Bash etc.)
- Type node -v
- This will print a version number if you do have node installed
You can see in this image the line where I’ve typed node -v and then pressed return, and then the subsequent response of the version number. You can use this for any npm package as well by typing packagename -v to find out if it’s installed, and if so, what version you have.
Summary
So to run a node.js file in Terminal (or command or git bash) you simply type ‘node‘ followed by the filename and include the .js extension:
node myfilename.js
…. and you’ll see something like this, i.e. a message telling you which port number your Node server is now running on.
Now that you’re up and running you may like to read my post which explains how to get data from an API using Node js.