Node.js basics cheatsheet

Download image version

Node package manager (NPM)

Node.js has a huge number of packages created by different developers that you can easily import into your projects using npm.

Basic console commands:

  • Create a package.json - configuration file that will describe the installed packages, scripts and application information:

npm init -y
  • Add package:

npm install package-name
  • Add package only for development:

npm install -D package-name
  • Delete package:

npm uninstall package-name

Run code

  • Running code Use command node + path to file to run it

node app.js
  • Running code with passing parameters

  • Environment variables dotenv is needed to load environment variables from .env file

Modules

  • CommonJS Modular system created specifically for Node.js

  • ES modules A modular system added to JavaScript in 2015. To enable it in Node.js, add the option ”type”: "module" to the package.json

Of course, the future belongs to ES modules. But there are still a number of difficulties associated with compatibility.

Working with paths

Node.js has a built-in path module for working with paths

Working with files

Node.js has a built-in fs module for working with files

  • Create/delete folders

  • Create/read/update/delete files

To ensure that all operations run in sync one by one, you can add Sync to each method name

System info

Node.js has a built-in os module for OS information

Events

Node.js allows you to create so-called Event Emmitters, which call special functions (Listeners) when an event is triggered.

Streams

The stream module allow you to read stream data in small chunks (64kb by default) There are 4 types of streams: Readable, Writable, Duplex (R + W) and Transform.

HTTP server

Server operations are the main application area fo Node.js

  • Basic http server

After starting the server, you can view it if open http://localhost://3000 on your browser.

For more convenient and fast creation of servers on Node.js uses various frameworks, such as Express.js, Fastify, Koa.js, Nest.js.

Last updated