DEV Community πŸ‘©β€πŸ’»πŸ‘¨β€πŸ’»

Maciej WakuΕ‚a
Maciej WakuΕ‚a

Posted on

Introduction to node and npm

1. Introduction

1.1. Target audience

This post is created especially for beginners and people who know some programming but are not familiar with node or npm.

1.2. Topics (not) covered

This is merely an introduction to node and npm (node package manager). It does not mention alternatives.

2. Node

2.1. About node

Node is a server-side runtime built on top of Google Chrome V8 javascript engine.
Node simply runs your javascript code on the server (without any browser window).

2.2. Usage

Simple usage: node myscript.js
Usually main file is called index.js

2.3. Setup

You can download node from https://nodejs.org/en/
You could also run it within a container, ex. by running docker run --rm -it node:lts bash (assuming you have docker installed).

2.4. Important notes about threading for developer not familiar with JavaScript

JavaScript is single threaded by design. It means that all the commands are executed sequentially but every chunk can be executed out of order.
Input/Output operations are multi-threaded though.
Knowledge of multi-threading from other languages is making things harder for you.
Try to divide your code into smaller chunks that end quickly. Example trap waiting for you is a "for" iteration which executed time consuming operation - you would block entire node process until iteration is completed.

Node is using either promises (a method call that is postponed but you could plan further calls based on its result) or async/await (which internally works on promises). See code example at the end.

If you are thinking that single-threading is bad then think again. Developer has possibly better control over the process than with multithreading one and you don't need to create a separate thread. Java is currently trying to implement similar mechanism with project loom. This solution brings some dangers though as developer can easily block the thread so your critical handlers (which are excepted to handle ex. keepalive requests) could not be called. Common unwanted effect is that your application gets disconnected from servers (database, rabbitMQ, kafka, etc.) or killed (ex. docker health checks).

3. Node Package Manager (npm)

https://www.npmjs.com/

3.1. What is npm

It is a manager application used to install, remove, update, check, ... your code but also an repository of immense amount of libraries and frameworks.

3.2. Npm packages

You could create own projects and publish them for free onto npmjs.org with public access (but also private access is available for paid accounts).
Projects that consist of several packages often are grouped into organizations like @babel. Organizations are prefixed with "@" character.

The npm ecosystem is very rich and has many packages. Amount of them is often used in jokes like with the npm drinking game.

3.3. Npm package versioning

Packages are released with tags, default tag is "latest". Any custom tag can be created but often tag "next" is used for any "unstable" releases.

Package versions should follow SemVer. Example number is 1.2.3 (major.minor.patch).
You should increase major number when introducing breaking changes (anything that could break apps using your package).
Minor number should be used when adding new features without breaking existing functionality.
Patch number is used for small bugfixes that do not break logic nor add new features.

By default when installing a package you would install most recently released version from "latest" tag (even if its number is lower than previously released one).
"Unstable" releases should be released under alternative tag and have additional suffix, ex. 1.2.4-next.0 to indicate that this is a pre-release version of upcoming 1.2.4 version under tag next, candidate number 0.
When auto-updating packages npm would try to stick with current major version (meaning "non-breaking changes only") but pick highest available "stable" version.
In fact there are no strict rules for the tags or versions.

3.4. Npm version update

You can use command npm version to update your version.
Example flow:

npm version 0.0.1  # versions starting with 0 are often considered to be not yet completed
npm version major  # bumps to 1.0.0 (breaking change)
npm version minor  # bumps to 1.1.0 (new feature)
npm version patch  # bumps to 1.1.1 (bugfix)
npm version prerelease --preid next  # bumps to 1.1.2-next.0
npm version prerelease --preid next  # bumps to 1.1.2-next.1
npm version minor  # bumps to 1.2.0
npm version prerelease --preid next  # bumps to 1.2.1-next.0
npm version patch  # bumps to 1.2.1
Enter fullscreen mode Exit fullscreen mode

Command npm version has a special logic when everuted from within a git repository - then a new commit with version update is created and a new annotated tag is created.

Keeping version in the source code has pros and cons. Most important cons is probably that version must be known "in advance" while many might prefer to have a build result (an artifact) which is tested and given its number after tests are passed.

3.5. Npm code scan

Npm has built-in commands for code scan:
npm outdated shows any packages having newer versions (beware of packages like stack-trace which has non-standard pre-release published on latest tag).
npm audit scans your code for known vulnerabilities.

4. Code examples

I might update the examples in the future

4.1. Async/Await example

async function myMethod(){
  const result1 = readFileAsync('/filename');
  console.log('This gets immediately printed BEFORE file is read');
  console.log(result1); // Prints "Promise" and is not yet resolved
  const result2 = await readFileAsync('/filename');
  console.log('This is not executed until result2 promise gets fulfilled').
  console.log(result2); // Prints result as it was already read
}

myMethod(); // Here I can use promises but not async/await - but I could "run" the async method "in the background"
Enter fullscreen mode Exit fullscreen mode

5. IDE (Integrated Development Environment)

Paid one https://www.jetbrains.com/webstorm/ (IntelliJ ultimate includes all its features).

Free one and providing very similar experience: https://code.visualstudio.com/

There are many other IDE's available (ex. https://atom.io/ which is written using node, javascript and npm).

Please let me know if you can find any issues with this post, do I can fix it. Also if you would like any topic to be added in this or another post.

Top comments (0)

Classic DEV Post:

Understanding git through images