Running a program
A Node.js program is an ordinary file with the .js extension. To run it, pass the file name to the node command. Node.js reads the code, executes it top to bottom and exits when there is nothing left to do.
The project folder
Create a folder for the blog and go into it:
mkdir blog
cd blogAll commands in the course are run from this folder.
The first program
Create the file app.js in the blog folder:
console.log('Hello from Node.js!');Run it:
node app.jsThe line "Hello from Node.js!" appears in the terminal. In Node.js console.log() writes to the terminal, not to the browser console.
The program exits by itself
Node.js keeps running while the program has work to do: pending timers, open connections, waiting promises. As soon as there is none left, the process ends:
console.log('Start');
setTimeout(() => {
console.log('One second passed');
}, 1000);
console.log('End of code');You see "Start" and "End of code", a second later "One second passed", and then the program exits. A server, by contrast, waits for requests forever — it is stopped with Ctrl+C.
Restarting on changes
To avoid starting the program again after every edit, add the --watch flag:
node --watch app.jsNode.js runs the file and watches it and the modules it imports. After you save, the program restarts by itself. This is handy while developing a server.
A few useful commands
| Command | What it does |
|---|---|
node app.js | Runs the file |
node --watch app.js | Runs it and restarts on changes |
node -e "console.log(2 + 2)" | Runs code from a string |
node --help | Shows all flags |
Common mistake
The command must be run from the folder that contains the file. Otherwise Node.js cannot find it:
Error: Cannot find module 'C:\Users\anna\app.js'Check the current folder with pwd (it works in Windows PowerShell too) and go to the project folder with cd.