πŸš€ Node.js πŸš€

Node.js is a modern JavaScript environment that can be used

  • πŸ—ƒοΈ To write websites (express handlebars...)
  • πŸ“¦ To write desktop/mobile apps (electron...)
  • 🍹 To create APIs (express...)
  • πŸ”₯️ To write Typescript (a typed JavaScript)
  • ✨ To write LESS/SASS/Stylus/... (improved CSS)
  • ... and many more

Where to learn?

You can download Node.js here. On Windows, you will get an installer, so you can get started in seconds. To check that your installation was successful, use

# see Node version
$ node -v
# run a JavaScript
$ node index
$ node index.js

πŸš€ To easily manage multiple versions of Node, see nvm (64k ⭐), nvm-windows (25k ⭐), or n (17k ⭐). Alternatively, there are nvs, nave, volta (7.3k ⭐), nodenv, fnm (9.8k ⭐), asdf and nodist.


Node.js basics

Packages

You will usually need to use external libraries such as a library to test your code, or stuff like that. They are referred to as packages, and you will need a package manager to install them.

➑️ One package worth mentioning is nodemon ("node-mon", 25k ⭐) which automatically restarts the node client (ex: node index.js) when a file in your project changes.


In a nutshell

Node.js includes everything you know about JavaScript, aside from the DOM (document, window...) as Node.js is NOT replicating an environment similar to a web browser.

What's new?

  • Import a package with require
// pre-installed, see https://nodejs.org/api/fs.html
const FileSystem = require('fs');

Access another script A from another script B

// in A.js, you need to export what you want to expose
module.exports = {}
module.exports.five = 5
// in B.js, use require
const A = require('./A.js')
console.log(A.five)

Node FileSystem (fs)

Import 'fs'

const fs = require('fs')

For async functions, you may use if (err) console.error(err);.

Read

const filedata = fs.readFileSync("path/to/file")
const filenames = fs.readdirSync("path/to/dir/")
// async
fs.readdir("data/wp/", (err, files) => { /* ... */ })

Write

fs.writeFileSync("path/to/file",  fileData, 'utf8')

Read/Write JSON files

// read
const json = JSON.parse(fs.readFileSync("path/to/xxx.json"))
// write
fs.writeFileSync("path/to/xxx.json", JSON.stringify(json, null, 2), 'utf8')

To be accurate, you should convert the Buffer to a string using fs.readFileSync("...").toString('utf8').

Rename/Move

// async
fs.rename(path, newPath, (err) => { /* ... */ });

πŸ‘» To-do πŸ‘»

Stuff that I found, but never read/used yet.

npm

  • devDependencies
  • winston test-debug http logs

tools