Encodera

Thanks for reading!

Donate to the site — we work hard for you.

Contents

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 blog

All 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.js

The 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.js

Node.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

CommandWhat it does
node app.jsRuns the file
node --watch app.jsRuns it and restarts on changes
node -e "console.log(2 + 2)"Runs code from a string
node --helpShows 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.

Thanks for reading!

Donate to the site — we work hard for you.