node js

Synopsis

Node.js is an open-source, cross-platform, back-end JavaScript runtime environment that runs on a JavaScript Engine and executes JavaScript code outside a web browser, which was designed to build scalable network applications.

Running Node JS

For running Node JS:

CommandDescription
nodeRun the Node REPL in your terminal
node —versionPrint your current Node version
node filename.jsExecute the Node code in filename.js

💡 REPL stands for Read Eval Print Loop. This is the list of steps that happen when you run the node command and then type some code.


Node JS Global Object

In Node, we have a global object that we can always access. Features that we expect to be available everywhere live in this global object. For example, to have some code execute after 5 seconds we can use either global.setTimeout or just setTimeout. The global keyword is optional.

setTimeout(() => {
  console.log("hello");
}, 5000);

The most famous global is global.console.log which we write as just console.log.

Node JS Module System

In Node.js, each file is treated as a separate module. Modules provide us a way of re-using existing code

The Required Function
We can re-use existing code by using the Node built-in require() function. This function imports code from another module.

const fs = require("fs");
fs.readFileSync("hello.txt");

// OR...

const { readFileSync } = require("fs");
readFileSync("hello.txt");

Built-in Modules
Some modules like fs are built in to Node. These modules contain Node-specific features.

Key built-in modules include:

Creating Modules
We can create our own modules by exporting a function from a file and importing it in another module.

// In src/fileModule.js
function read(filename) {}
function write(filename, data) {}

module.exports = {
  read,
  write,
};

// In src/sayHello.js
const { write } = require("./fileModule.js");
write("hello.txt", "Hello world!");

Some Node modules may instead use the shorthand syntax to export functions.

// In src/fileModule.js
exports.read = function read(filename) {};
exports.write = function write(filename, data) {};

ECMAScript Modules
The imports above use a syntax known as CommonJS (CJS) modules. Node treats JavaScript code as CommonJS modules by default. More recently, you may have seen the ECMAScript module (ESM) syntax. This is the syntax that is used by TypeScript.

// In src/fileModule.mjs
function read(filename) {}
function write(filename, data) {}

export { read, write };

// In src/sayHello.mjs
import { write } from "./response.mjs";
write("hello.txt", "Hello world!");

We tell Node to treat JavaScript code as an ECMAScript module by using the .mjs file extension. Pick one approach and use it consistently throughout your Node project.

Node JS Package Manager

Node developers often publicly share packages, that other developers can use to help solve common problems. A package is a collection of Node modules along with a package.json file describing the package.

To work with Node packages we use NPM. NPM includes two things:

  1. The NPM registry with a massive collection of Node packages for us to use.
  2. The NPM tool that you installed when you installed Node.

NPM COMMANDS

CommandDescription
npm startExecute the current Node package defined by package.json
Defaults to executing node server.js
npm initInitialize a fresh package.json file
npm init -yInitialize a fresh package.json file, accepting all default options.
Equivalent to npm init —yes
npm installEquivalent to npm i
npm install Install a package from the NPM registry at www.npmjs.com
Equivalent to npm i
npm install -D Install a package as a development dependency
Equivalent to npm install —save-dev
npm install -g Install a package globally.
npm update Update an already installed package
Equivalent to npm up
npm uninstall Uninstall a package from your node_modules/ folder
Equivalent to npm un
npm outdatedCheck for outdated package dependencies
npm auditCheck for security vulnerabilities in package dependencies
npm audit fixTry to fix any security vulnerabilities by automatically updating vulnerable packages

package.json
Most Node applications we create include a package.json file, which means our Node applications are also Node packages. The package.json file contains:

  1. Name, version, description, license of the current package.
  2. Scripts to automate tasks like starting, testing, and installing the current package.
  3. Lists of dependencies that are required to be installed by the current package.

node_modules
This folder lives next to your package.json file.
When you run npm install the packages listed as dependencies in your package.json are downloaded from the NPM registry and put in the node_modules folder.
It contains not just your direct dependencies, but also the dependencies of those dependencies. The entire dependency tree lives in node_modules.

package-lock.json
The package-lock.json file is automatically created by NPM to track the exact versions of packages that are installed in your node_modules folder. Share your package-lock.json with other developers on your team to ensure that everyone is running the exact same versions of every package in the dependency tree.

Node JS Event Emitter

Node JS provides a built-in module to work with events.

const EventEmitter = require("events");
const celebrity = new EventEmitter();

celebrity.on("success", () => {
  console.log("Congratulations! You are the best!");
});

celebrity.emit("success"); // logs success message
celebrity.emit("success"); // logs success message again
celebrity.emit("failure"); // logs nothing

Many features of Node are modelled with the EventEmitter class. Some examples include the currently running Node process, a running HTTP server, and web sockets. They all emit events that can then be listened for using a listener function like on().

For example, we can listen for the exit event on the current running process. In this case, the event has a code associated with it to be more specific about how the process is exiting.

const process = require("process");

process.on("exit", (code) => {
  console.log(`About to exit with code: ${code}`);
});

Backends with Node JS

Client-server architecture
Your frontend is usually the client. Your backend is usually the server.
In a client-server architecture, clients get access to data (or “resources”) from the server. The client can then display and interact with this data.
The client and server communicate with each other using the HTTP protocol.

API
Short for Application Programming Interface.
This is the set of functions or operations that your backend server supports. The frontend interacts with the backend by using only these operations.
On the web, backend APIs are commonly defined by a list of URLs, corresponding HTTP methods, and any queries and parameters.

CRUD
Short for Create Read Update and Delete.
These are the basic operations that every API supports on collections of data. Your API will usually save (or “persist”) these collections of data in a database.

RESTful
RESTful APIs are those that follow certain constraints. These include: