Node.js

Node.js

Introduction

Node.js® in a nutshell is a JavaScript runtime for server-side, as well as client-side applications, as opposed to the JavaScript that runs in browsers. You can learn more about Node.js here, as this page is just to give you a quick start guide for new Node.js applications.

npm, of which the CLI is installed with Node.js, is a software registry and repository for open source developers to share and download packages.

Getting Started

Install

The easiest way to install Node.js is using an installer (if you’re using Windows or macOS), you can find these on their download page along with binaries for Linux, or you can install via package manager.

Test

To make sure Node.js has been installed ok, open up a command prompt / terminal and type the following — this should display the version installed…

> node -v v16.15.0

…and the same for npm…

> npm -v 9.2.0

Create

To create a new Node.js application / package, first you need to create a directory/folder…

> mkdir new-app

…and change into this new directory/folder…

> cd new-app new-app> _

…then we need to initialise and create a package.json file. This process will take you through a series of prompts, and with most you can just hit ENTER for the default…

new-app> npm init This utility will walk you through creating a package.json file. It only covers the most common items, and tries to guess sensible defaults.
See `npm help init` for definitive documentation on these fields and exactly what they do.
Use `npm install <pkg>` afterwards to install a package and save it as a dependency in the package.json file.
Press ^C at any time to quit. package name: (new-app) version: (1.0.0) description: New Node.js application entry point: (index.js) app.js test command: git repository: keywords: author: Neil Deighan license: (ISC) About to write to /new-app/package.json:
{ “name”: “new-app”, “version”: “1.0.0”, “description”: “New Node.js application”, “main”: “app.js”, “scripts”: { “test”: “echo "Error: no test specified" && exit 1” }, “author”: “Neil Deighan”, “license”: “ISC” }

Is this OK? (yes) y

Using your favourite code editor, you can then create the main app.js file. Here is an example of a client / console application…

// *************************************
// app.js
//
// Console based Node.js application
//
// *************************************

// Requires built-in readline module
const readline = require("readline");

// Create new readline interface for a user profile
const profile = readline.createInterface({
    input: process.stdin,
    output: process.stdout
});

// Ask questions ...
profile.question("What is your name? ", (name) => {
    profile.question("What is your email? ", (email) => {
        // ... and display answers
        console.log(`Hello ${name}, we will send all notifications to ${email}`);
        // close interface
        profile.close();
    })
})

// .. when interface is closed ..
profile.on("close", () => {
    // ... show goodbye message
    console.log("Thank you for providing profile information, goodbye");
    // exit
    process.exit(0);
});

…and to run the application from a command/terminal window…

new-app> node app.js What is your name? Neil What is your email? blog@neildeighan.com Hello Neil, we will send all notifications to blog@neildeighan.com Thank you for providing profile information, goodbye

Packages

Local

If your application requires a third-party package, say Express, you would need to run the following to install the latest stable version…

new-app> npm install express
added 57 packages, and audited 58 packages in 7s
7 packages are looking for funding run `npm fund` for details
found 0 vulnerabilities

…this would add dependencies to the package.json file…

{
  "name": "new-app",
  "version": "1.0.0",
  ...
  "dependencies": {
    "express": "^4.18.2"
  }
}

…and install the package and its own dependencies into the local node_modules folder. It also creates a package-lock.json file, which, if not deleted, will on subsequent npm install install packages based on the versions in this lock file.

Development

It may be that you want to install a package that you only need for the development of your application, and that is not used by it in production — say, a testing framework such as Mocha. This would be installed as follows, note the --save-dev option…

new-app> npm install mocha --save-dev
added 75 packages, and audited 133 packages in 7s
26 packages are looking for funding run `npm fund` for details
found 0 vulnerabilities

…this would add devDependencies to the package.json file…

{
  "name": "new-app",
  "version": "1.0.0",
  ...
  "dependencies": {
    "express": "^4.18.2"
  },
  "devDependencies": {
    "mocha": "^10.2.0"
  }
}
Global

If you are installing packages that need to be accessible across your projects — say, Firebase Tools — you would install as shown below, note the --global option (which can also be shortened to -g)…

> npm install firebase-tools --global
added 701 packages in 7s
46 packages are looking for funding run `npm fund` for details
found 0 vulnerabilities

…unlike local packages, global packages are not added to package.json. You can list all globally installed packages with…

> npm ls --global --depth=0 /usr/local/lib ├── firebase-tools@12.0.0 └── npm@9.2.0

Versions

It is very much worth reading more about the Semantic Versioning (semver) system used for packages. The knowledge can come in very handy when faced with dependency hell.

Source Control

It is highly recommended that you include the package-lock.json file along with the package.json file in source control. This will ensure that when you run npm install on a new clone of your repository it will install the precise versions required.

You do not want to include the node_modules folder in your repository. If using git, exclude it by adding to a .gitignore file…

# Ignore node_modules
node_modules

Further Reading

Conclusion

Just a short overview of how to install and test Node.js, as well as creating a basic application, with a few notes on different types of package installations, versioning, and source control tips.