What is Node.js?
Node.js is an environment that lets you run JavaScript outside the browser, for example on your computer or on a server. It uses the same engine as Chrome (V8) and opens the door to building web servers, command-line tools and much more.
# Run a file with Node
node app.js
npm and package.json
npm (Node Package Manager) is Node's package manager. With it you install libraries that other people have published.
npm init -y # creates a package.json
npm install lodash # installs a dependency
npm install --save-dev jest # development dependency
The package.json file describes your project: its name, version,
dependencies and scripts.
{
"name": "my-project",
"version": "1.0.0",
"scripts": {
"test": "jest",
"start": "node app.js"
},
"dependencies": {
"lodash": "^4.17.21"
}
}
The scripts are run with npm run <name> (or npm test, npm start
for the special ones).
The
node_modulesfolder (where dependencies are installed) is not pushed to the repository: it is regenerated withnpm installfrom thepackage.json.
Examples
Read data from package.json (simulated)
const pkg = {
name: "my-project",
version: "1.0.0",
scripts: { test: "jest", start: "node app.js" },
};
console.log("Project:", pkg.name, "v" + pkg.version);
console.log("Available scripts:", Object.keys(pkg.scripts));