Node JS is a JavaScript engine which can run JavaScript outside of the browser.
You can grab the Node JS app which also comes with NPM, Node Package Manager from nodejs.org. There are two versions, LTS and current. The LTS version is probably the best. LTS stands for Long Term Support and some apps only run on this version. There again for things using the latest tech the current version might be what you need.
To run Node simply open a terminal and type node
. You can now type and execute Javascript code directly in the terminal and without a browser. To quit press Ctrl + D
or type .exit
. Using Ctrl + C
will stop the current function.
You can also run a javascript file inside Node. Just type node app.js
where app.js is the name (and path if necessary) of your JS file.
Not everything works in Node JS since some things are specific to browsers. So you can’t use alert()
in Node JS for instance.
There is no window or document object in Node. The equivalent of the window object in Node is the global object.
Modules
Variables are not scoped to the global object only to their module, which is typically the file they’re in. Every file is a different module. This prevents the problem of having two or more variables with the same name declared in different files. This means that variables are not available outside of their module by default.
A node app can be made up of multiple modules but there is at least one main module.
If you run a JavaScript file from Node with just console.log(module)
you get something like this:
Module {
id: '.',
path: 'C:\\projects\\js-blog\\static\\js',
exports: {},
filename: 'C:\\projects\\js-blog\\static\\js\\blank.js',
loaded: false,
children: [],
paths: [
'C:\\projects\\js-blog\\static\\js\\node_modules',
'C:\\projects\\js-blog\\static\\node_modules',
'C:\\projects\\js-blog\\node_modules',
'C:\\projects\\node_modules',
'C:\\node_modules'
]
}
On the fourth line are exports
which is where functions and variables within the file are exported.
To export a variable or a function from inside the module use:
const myVar = 730;
module.exports.myVar = myVar;
To get export just the value of myVar
:
module.exports.endPoint = myVar;
Note the syntax of ES6 modules is different. VS Code may offer to convert a file to an ES6 module.
Using the module
To access the exported module you use require()
. If you’re using a file in the same directory called my-info.js it would be:
require('./my-info');
The .js
extension is unnecessary because Node assumes it is a JS file.
The require()
function is not part of ECM (official JavaScript). There is import()
which works similarly but you cannot use it with JSON files. Which should you use? As always it depends. There is a comparison on MasteringJS.io
There is a lot more on Node is this video by Mosh.