Trainings: learnyounode, freecodecamp, codebuffon, simplifynodejs
- Installing Node help
- Node basics - how to start
- FAQ about broken Promises, how to Express yourself
- Yarn & npm - dependency managers
- Testing Node - Chai, Mocha, Sinon
- Going to production - build, dockerizing
- Good to know - personal experiences and recommendations
- Example repos
- Format code
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)
sudo apt-get update
sudo apt-get install nodejs
brew install node
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
-
variable name: NODE_PATH
D:\Program\nodejs\node_modules\npm\node_modules
D:\Program\npm\node_modules
-
User Path
addD:\Program\npm
-
variable name: NODE_MODULES
D:\Program\nodejs\node_modules\npm\node_modules
-
variable name: NODE_PATH
D:\Program\nodejs
-
System Path
D:\Program\nodejs\
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:
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
- refresh npm
npm install npm -g
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
.
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
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.
new Promise
done()
bluebird
resolve
reject
await
- Node.js is an environment that lets you run JavaScript on the server.
- It does this by using V8 (C++ written engine, you can find the same in Chrome) to run JavaScript
- 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.
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
- 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
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
an alternate for npm. Its biggest differentiators are included in npm yet but it is still a very good choice with a lovely design.
Mac: get it with homebrew package manager: brew install yarn
.
- ! If you use nvm, you should install yarn without node:
brew install yarn --without-node
Win: use chocolatery package manager choco install yarn
for windows or simply download and run installer msi file
Linux: use apt-get
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
- create package.json with defaults
npm init --yes
- scope
TBD - update all the global packages
npm update -g
- list all the globally installed packages
npm list -g --depth=0
- install a specific version of the package
npm install -g [email protected]
npm install eslint-plugin-import@^2.2.0
depcheck is to find dependencies
npm install depcheck -g Run it and find the unused dependencies:
depcheck
TBD
"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
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
joyent's article about Error Handling in Node.js
Http-errors - Http-errors repo
Supertest repo
Supertest: Things I've learned - by Marcus Hammarberg
testdouble repo
testdouble for Jest
partial mock question
Intro video
-
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
How to Dockerize a Node.js application
(buddy.com)
Helpers and tips for npm run scripts
You can colorize your terminal output with these colours.
enduro.js - does not work on Win well, this issue is not resolved for a long time which does not help trust
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
Repositories to learn and practice node
This projects shows actual bitcoin values in three top currencies. It is a Next.js app
Electron's official example repos to learn
a short video guide
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 .