Node and npm

Node and npm: overview

Node and npm: overview

Node.js is a JavaScript runtime

It may be used to:

  • run scripts locally
  • provide development tools (e.g. for build process, unit tests, ...)
  • run a backend

Node and npm: overview

npm = Node package manager

is included in the node.js installation

Installation

Download from https://nodejs.org

Major releases every 6 months; long-term-support releases every 12 months

npm

npm registry

The npm registry is an online registry consisting primarily of open source JavaScript packages

examples: most depended upon packages

Package managers

major package managers for the npm registry:

  • npm: Node package manager, comes with node.js
  • pnpm
  • yarn

Package configuration

Both public packages and private projects are managed via a configuration file named package.json

Package configuration

In order to add dependencies - start out with an empty package.json configuration:

{}

Alternative: create a package.json with some content via via npm init (or npm init -y for default options)

Adding dependencies

Add dependencies via e.g.:

npm install lodash bootstrap

Adding dependencies

When developing a reusable library to be published on the npm package registry:

Install dependencies that are only needed for development as dev-dependencies:

npm install eslint --save-dev

Adding dependencies

Effects of the previous npm install commands:

  • package.json - lists minimum versions of the packages we just installed
  • node_modules - folder that contains all installed packages
  • package-lock.json - lists exact versions of all packages in node_modules

Dependencies in package.json

The file package.json now lists dependencies together with a version specifier

The version specifier typically uses semantic versioning: major.minor.patch

possible configurations:

  • "bootstrap": "4.3.1" - exactly this version
  • "bootstrap": "~4.3.1" - patch version updates allowed - for example to 4.3.2
  • "bootstrap": "^4.3.1" - minor version updates allowed - for example to 4.4.0

Dependencies in package-lock.json

package-lock.json lists exact versions for all dependencies and their recursive dependencies

node_modules folder

contains the actual packages

this should not be put under version control - can be recreated from package.json by running npm install (without any arguments)

npm scripts

Npm can be used to execute scripts / commands that are needed for development, for example:

  • npm run test - would run unit tests
  • npm run build - would create a build
  • npm run start
  • npm run deploy

Some npm scripts have shorthands, notably npm test and npm start

npm scripts

Npm scripts are configured in package.json:

{
  "scripts": { "start": "node run-server.js" }
}

Global installs and npx

Node packages may be installed globally on a computer or may be executed directly from the npm registry

direct execution (without installation):

npx cowsay hello

global installation of cowsay:

npm install -g cowsay

cowsay hello

Running node programs

Running programs in the terminal

hello.js:

console.log('Hello world!');

running it:

node hello.js

Running programs in VS Code

with debugging: F5

without debugging: Ctrl + F5

Running programs in VS Code

to determine how a JavaScript file should be run:

with a JavaScript file open, open the "Run" sidebar

select create a launch.json file - Node.js to create a file under .vscode/launch.json

Running programs in VS Code

possible configuration entries (.vscode/launch.json):

{
  "name": "Run current file",
  "type": "node",
  "request": "launch",
  "program": "${file}",
  "skipFiles": ["<node_internals>/**"]
}
{
  "name": "Run index.js",
  "type": "node",
  "request": "launch",
  "program": "${workspaceFolder}/index.js",
  "skipFiles": ["<node_internals>/**"]
}

Modules

Modules

Node programs can import objects from so-called modules

3 categories:

  • built-in modules
  • modules from npm
  • modules in the local directory

Importing modules

standard JavaScript imports:

import { platform, release } from 'os';

older, node-specific variant:

const { platform, release } = require('os');

Importing modules

to use the import syntax in a node project, declare it as a module in package.json:

{
  "type": "module"
}

Local modules

Local modules

A JavaScript file that exports objects is called a module

Local modules

example of a module with modern syntax:

const message1 = 'hello!';
const message2 = 'have a nice day!';

export { message1, message2 };

Local modules

there may be one default export

const mainMessage = 'xyz';

const message1 = 'hello!';
const message2 = 'have a nice day!';

export { message1, message2 };
export default mainMessage;

Local modules

local modules are referenced via relative file paths:

import mainMessage, { message1 } from './messages.js';

in node, the filename extension is optional:

import mainMessage, { message1 } from './messages';

Local modules

older, node-specific, export syntax:

const message1 = 'hello!';
const message2 = 'have a nice day!';

module.exports.message1 = message1;
module.exports.message2 = message2;
// shorthand
exports.message3 = 'Bye';

default export:

const mainMessage = 'xyz';

module.exports = mainMessage;

Globals and built-in modules

Globals

node has different global objects than in the browser

Globals

browser-only globals:

  • document
  • localStorage, sessionStorage
  • window (global namespace) - alternative name globalThis
  • ...

node-only globals:

  • process (e.g. process.argv)
  • __filename and __dirname
  • global (global namespace) - alternative name globalThis
  • ...

Built-in modules

  • assert
  • fs (file system)
  • http(s)
  • net (TCP)
  • os
  • path
  • ...

Process

Process

process is a global

  • process.argv (command line arguments)
  • process.cwd()
  • process.exit()
  • ...

Process

exercise: implement a program that can be run like this:

node sum.js 1 2 3

output:

the sum is 6

Reading and writing files and folders

Reading and writing files and folders

Examples:

asynchronous via promises (recommended):

import { readFile } from 'node:fs/promises';

asynchronous via callbacks:

import { readFile } from 'node:fs';

synchronous:

import { readFileSync } from 'node:fs';

Writing text files

import { writeFile } from 'node:fs/promises';

await writeFile('message.txt', 'hello world');

This will write to a text file in UTF-8 encoding.

Reading text files

const fileContent = await readFile('package.json', 'utf8');

When reading files as text, we must specify an encoding (in this case, UTF-8)

Reading folder content

const folderContent = await readdir('.');

console.log(folderContent);

HTTP server with node

Running an HTTP server with node

import http from 'http';

const requestHandler = (req, res) => {
  res.statusCode = 200;
  res.setHeader('Content-Type', 'text/plain');
  res.end('Hello World\n');
};

const server = http.createServer(requestHandler);

server.listen({ port: 3000 });

(see https://nodejs.org/en/docs/guides/getting-started-guide/)

HTTP server frameworks

  • connect: middleware
  • express: middleware, routing