Node
Node is a serverside technology to run JavaScript
Sometimes, the browser does not know how to interpret commands (such as require). To get around this we can use Browserfiy or Webpackto run Node scripts in the browser
Adding packages to a project
Navigate to project directory, and start with npm init:
cd path/to/project/javascript
npm initThis will walk you through creating a package.json file, starting with the name of the package.
Once this file isn created we can begin using npm and installing packages:
npm i <package> --save
Doing this will automatically add a “dependencies” line to the package.json file. For example:
# In ../node_npm/
ls
-> main.js index.html
node init
-> package.json main.js index.html
Note
You can use the
--save-devflag to create development dependencies, which are not needed while the project is running but are required to build it, such as tests, local servers, etc
When npm is initialized, the json file looks as follows:
1 │ {
2 │ "name": "node_npm",
3 │ "version": "1.0.0",
4 │ "main": "main.js",
5 │ "scripts": {
6 │ "test": "echo \"Error: no test specified\" && exit 1"
7 │ },
8 │ "author": "",
9 │ "license": "ISC",
10 │ "description": ""
11 │ }Then, if in the same directory we install a package → npm i moment:
// package.json
{
"name": "node_npm",
"version": "1.0.0",
"main": "main.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"author": "",
"license": "ISC",
"description": "",
"dependencies": {
"moment": "^2.30.1" // Note the addition of this dependency
}
}Additionally, running this will install a “node_modules” directory int he project root, which includes the modules installed (basically downloads the modules’ repository, including README and their own required files)
This is also a package-lock.json file created along package.json, which has all the specific details about the installed packages. Continuing with the example above:
// package-lock.json
{
"name": "node_npm",
"version": "1.0.0",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "node_npm",
"version": "1.0.0",
"license": "ISC",
"dependencies": {
"moment": "^2.30.1"
}
},
"node_modules/moment": {
"version": "2.30.1",
"resolved": "https://registry.npmjs.org/moment/-/moment-2.30.1.tgz",
"integrity": "sha512-uEmtNhbDOrWPFS+hdjFCBfy9f2YoyzRpwcl+DqpC6taX21FzsTLQVbMV/W7PzNSX6x/bhC1zA3c2UQ5NzH6how==",
"license": "MIT",
"engines": {
"node": "*"
}
}
}
}