Running Node.js
Once Node.js is installed, you run JavaScript outside the browser using the node command or npm scripts.
The REPL
Type node in your terminal to open an interactive prompt. It is useful for quick experiments and testing expressions.
$ node
> 1 + 1
2
> 'hello' + ' world'
'hello world'
> .exit
Type .exit or press Ctrl+C twice to exit.
Inline eval with -e
Run a single expression without creating a file:
node -e "console.log(new Date())"
node -e "console.log(process.versions.node)"
This is handy in shell scripts and one-off checks.
Running a file
This is the most common approach. Create a .js file and run it with node:
node app.js
node app # .js extension is optional
node ./src/app.js # relative path works too
If you have an index.js in the current directory, you can run it with:
node .
npm scripts
Define scripts in package.json so you don’t have to type long commands:
{
"scripts": {
"start": "node index.js",
"dev": "nodemon index.js"
}
}
Run them with:
npm start # runs the start script
npm run dev # runs any named script other than start and test
npm start and npm test are special: they do not need the run keyword. Every other script name does.