Node.js and npm (Node Package Manager) are essential tools for modern web development. Node.js is a runtime environment that allows you to run JavaScript on the server side, while npm is a package manager that helps you install, update, and manage JavaScript packages (libraries and tools). The following notes assume Node and npm have been installed using instructions from the official website.
Basics
- Initialize a new npm project by creating a
package.jsonfile. This file keeps track of your project’s dependencies and configurations. The-ykeeps the process short without being prompted of a lot of redundant options.
npm init -yRemember for this default flag -y npm always assumed the main js file is index.js so name it accordingly.
-
To install a package (e.g., Express for creating web servers), use the
npm installcommand ornpm i. This installs the package locally which means it is installed only for this project. Any install command will create anode_modulesfolder in your project directory and install all dependencies there. -
To install a package globally (available system-wide), use the -g flag:
npm install -g nodemon- To remove a package, use the uninstall command:
npm uninstall express- To update a package to the latest version, use the update command:
npm update express- To list all the packages installed in your project:
npm listSetting up and running a Node project
If a refresher on general file/folder structure of node applications are needed, check out File Structure for a Node.js Application before running a project to have a clear overview.
- Firstly, check for
package.json. The presence of apackage.jsonfile in the root directory of the repository indicates that it’s a Node.js project. Open thepackage.jsonfile to see the project details.
An existing project already has the required dependencies listed on package.json file. This means simply install it using this command:
npm install- If the project needs to be built before running, look for a
buildscript inpackage.jsonand run:
npm run build- Next, check for
scriptsinpackage.json. Open thepackage.jsonfile and look for thescriptssection. This section defines various commands to run your project. An example includingstart,build,test, etc:
"scripts": {
"start": "node index.js",
"build": "webpack --config webpack.config.js",
"test": "jest"
}- Now we can probably run the project. The start script is already there so we can simply
npm startto start running the project.