Skip to content

Instantly share code, notes, and snippets.

@somahargitai
Last active February 13, 2024 14:01
Show Gist options
  • Save somahargitai/ac03fdd9d94a9b1d93785d62dd756dd9 to your computer and use it in GitHub Desktop.
Save somahargitai/ac03fdd9d94a9b1d93785d62dd756dd9 to your computer and use it in GitHub Desktop.
Node.js cheatsheet

cheatsheet list

Node Cheatsheet

Node.js documentation

Trainings: learnyounode, freecodecamp, codebuffon, simplifynodejs

Contents

  1. Installing Node help
  2. Node basics - how to start
  3. FAQ about broken Promises, how to Express yourself
  4. Yarn & npm - dependency managers
  5. Testing Node - Chai, Mocha, Sinon
  6. Going to production - build, dockerizing
  7. Good to know - personal experiences and recommendations
  8. Example repos
  9. Format code

0. Installing Node Help - environmental variables

still working on this part

important note: install nvm, npm and node together. You will need all of them.

(On Mac and GNU/Linux you can use n instead of nvm too. It does basicly the same)

GNU/Linux

sudo apt-get update
sudo apt-get install nodejs

Mac

brew install node

Win

Installing node js is quite straight-forward. But if you would like to install it to another drive, don't forget to set/update environmental variables after installation. For example, you install node to D:\Program\nodejs and you would like to install everything to D:\Program\npm and D:\Program\nodejs.

I use the so-called Bash on Linux on Windows a.k.a. Windows Subsystem for Linux (install it here). In this terminal the Linux install did not work, so I used:
curl -sL https://deb.nodesource.com/setup_10.x | sudo -E bash -
sudo apt-get install -y nodejs

User variables

  • variable name: NODE_PATH
    D:\Program\nodejs\node_modules\npm\node_modules
    D:\Program\npm\node_modules

  • User Path
    add D:\Program\npm

System variables

  • variable name: NODE_MODULES
    D:\Program\nodejs\node_modules\npm\node_modules

  • variable name: NODE_PATH
    D:\Program\nodejs

  • System Path
    D:\Program\nodejs\

node_modules

Default folder for global node_modules in Windows is {APPDATA}\npm which means all your modules will be settled in C:\Users\User\AppData\Roaming\npm. It is setted in {node_installation_folder}\node_modules\npm\npmrc file, in this context: D:\Program\nodejs\node_modules\npm\npmrc. Change default prefix=${APPDATA}\npm to the folder you wish. In my computer I have a folder for programs on D:\ drive. I store its path in an environmental variable called DPROGRAM, so my nprmc file value is prefix=${DPROGRAM}\npm. If you don't want to delete the original content of this file, you can comment that line with a semicolon like: ; prefix=${APPDATA}\npm.

.npmrc, .nvmrc and others

.npmrc:

https://www.roblahoda.com/blog/where-is-the-npmrc-file.html

https://docs.npmjs.com/files/npmrc

.nvmrc file defines node version in the project folder

.tsconfig

1. Node basics

first install / refresh !

  • refresh npm
    npm install npm -g

2. FAQ:

Import vs Require howto

You have to enable using ES6 import and export. It is expected to be part of Node.js default settings, but for now you have to do it with a third party tool.

Today most popular is Babel. You will run your code from a start.js file which will import Babel and your code, then transpile. See this text project about how to create a very basic Express.js API.

Oldschool Module require and ES6 export/import system are compatible! The only special case is that you may require a module which is exported as default. In that case you should use it like const mypackage = require('./path/mypackage').default.

Examples you may see

import someApi from '../path/some-api';
import { someApi } from '../path/some-api';
import { someApi1, someApi2, someApi3 } from '../path/some-api';
import * as someApi from '../path/some-api';
const someApi = require('../path/some-api');
const someApi = require('../path/some-api').default;

Find more options and how-tos on this javascript.info article

Export practices

Some people use strict rules about exporting. For example many ban default exporting by setting default export to an empty object and exporting functions individually.

Another practice is that people use individual export const functionname = () = { ... } AND they also export one of the functions as default. It may be helpful to identify the main functionality, enables them to use small functions and also enables renaming functions in imports - sometimes it is necessary if you have two functions with the same name and it is not allowed to rename a named export, so you will have to use default export.

async, non-blocking, Promise

Promise - what is it and how to use it

new Promise
done()
bluebird
resolve
reject
await

What is V8 and libuv? How does node.js look like inside?

  1. Node.js is an environment that lets you run JavaScript on the server.
  2. It does this by using V8 (C++ written engine, you can find the same in Chrome) to run JavaScript
  3. Think of libuv* as a bridge to the OS. So you can run OS specific code (file system, sockets, etc) in javascript as it interacts with libuv.

Express.js and other "default" libraries

What is Express.js? Why is it necessary? Can we solve these functionalities with pure Node.js?

One of the libraries that is part of the node standard library is http. Http lets you write an http server on the OS and every request that comes into the binded port will call the http server's callback with the parameters for request and response. You can handle that code directly without Express.

Express is just a javaScript framework that attaches to this callback and makes it easier to work with those requests. Express.js is just one such framework, you also have access to Koa.js, and Hapi.js (and many others). Express is just the oldest and most widely used but not necessarily the best. These frameworks are NOT part of node, they are just libraries and frameworks made by other developers that make it easier to work with the http node standard library.

Thanks for Therealgem Josh and Edward Boyle for the answers under this facebook post

must-have tools

  • Joi is a useful tool to validate specific data formats. For example you want to have an object having a birthdate property which allow only values between 1910 and 2019. Check out this tutorial for more. Of course if you use typescript, you may find a different approach, as ts provides interfaces and types

3. Yarn & npm - dependency managers

These tools are downloading your dependencies - used libraries - for your project and also provide features like defining your own scripts. They store your dependency list in a file called package.json, pull dependencies to node_modules folder and create the so-called lock-files (package-lock.json or yarn.lock). In your package.json dependency list you will see lines like "typescript": "3.4.5", with characters like >=0.0.0, ~1.2.3-beta.2, 1.x . To understand its syntax check npm semantic versioner readme

yarn

an alternate for npm. Its biggest differentiators are included in npm yet but it is still a very good choice with a lovely design.

Installation

Mac: get it with homebrew package manager: brew install yarn.

Win: use chocolatery package manager choco install yarn for windows or simply download and run installer msi file

Linux: use apt-get

npm

classic package manager for node and for any other Javascript project,
default install location of node_modules is defined in nodeInstallFolder\nodejs\node_modules\npm\npmrc file

depcheck is to find dependencies

npm install depcheck -g Run it and find the unused dependencies:

depcheck

npx

TBD

Yarn and npm config and proxy

"npm gets its config settings from the command line, environment variables, and npmrc files."(npm docs).

We store configuration information in .npmrc and in .yarnrc files, typically proxy settings. I place here examples how mine looks like. It is also a good reminder for developer behind corporate proxies.

You can edit directly these files but usually it is not recommended, so see config commands in documentation.
like: yarn config set strict-ssl false

.yarnrc

# THIS IS AN AUTOGENERATED FILE. DO NOT EDIT THIS FILE DIRECTLY.
# yarn lockfile v1

https-proxy "http://someserver.proxy.company.com:80/"
lastUpdateCheck 1232026156080
proxy "http://someserver.proxy.company.com:80/"
strict-ssl false

.npmrc

PROXY:=http://someserver.proxy.company.com:80/
https-proxy=http://someserver.proxy.company.com:80/
proxy=http://someserver.proxy.company.com:80/
strict-ssl=false

dependencises and versions

  node --version && npm --version
  • for depencencies use npm or yarn

  • for node versions use nvm

  • delete node modules and reinstall them rm -rf node_modules/ npm install
    npm uninstall -g enduro remove global package

  • update npm
    sudo npm install -g npm

  • node version manager nvm use - updates node version to use the appropriate one

node -v
node --version
nvm install 8

  • set default node version
    nvm alias default 6.1.0

  • network Setup proxy Try internal and open network too

Of course sometimes you should use sudo

Errors

joyent's article about Error Handling in Node.js

Http-errors - Http-errors repo

Tests

Libraries for Node.js testing

Jest

jest repo

Supertest

Supertest repo
Supertest: Things I've learned - by Marcus Hammarberg

Testdouble

testdouble repo
testdouble for Jest
partial mock question
Intro video

Proxyquire

Proxyquire repo

Mocha

  • mocha docs
    mocha --help

mocha -R spec filename.js

  • Mocha test on a specific test file // backend
    mocha test/functions/somefolder/someTest.js
    adding a node_env variable:
    NODE_ENV=prod mocha test/functions/somefolder/sometest.js
    Running on test only or skipping one:
    it.only()
    it.skip()
    TBD test -> this will return with blue response without error . it('should map something');

--- proxyquire var proxyquire = require('proxyquire').noPreserveCache(); , it just set the ec2Mapper back to the default, as it was suppose to, and our proxy require for the ec2Instance mapper didn’t work, because we didn’t pass it into the ebsMapper proxyrequire

5. Going to production - build, dockerizing

How to Dockerize a Node.js application (buddy.com)
Helpers and tips for npm run scripts

6. Good to know - personal experiences and recommendations

Customize to fit your personal preferences

You can colorize your terminal output with these colours.

Node CMS

enduro.js - does not work on Win well, this issue is not resolved for a long time which does not help trust

Environmental variables

It may be painful to use it on different environments, so make sure it works on multiple platforms by adding cross-env to your package.json. Use it in your scripts like

"start": "cross-env VARIABLE=yourvalue node start.js"

DB_LOGGING=1 npm run applicationname npm test nvm use npm install proxyon / proxyoff

7. Example repos and tutorials

Repositories to learn and practice node

This projects shows actual bitcoin values in three top currencies. It is a Next.js app

Electron

Electron's official example repos to learn

a short video guide

8. Format code

install

npm install --save-dev prettier

.prettierrc file:

{
    "useTabs": false,
    "tabWidth": 4,
    "singleQuote": true,
    "trailingComma": "es5"
}

Autoformat from terminal

npx prettier --write your-file.js
npx prettier --write "**/*.js"

Check formatting without modifying anything

npx prettier --check your-file.js your-other-file.js
npx prettier --check .
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment