π 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?
- Documentation (βͺ)
- Tutorials (π) / Knowledge (old)
- Runkit (online playground)
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.
- .env / nconf / node-config
- See JavaScript, what are modules/...?
- bcrypt
- http2 server-push
- nodebestpractices
- commander (CLI interface)
- Verdaccio