I never disliked JavaScript much for simple web stuff, never especially liked it either tho :)
But the past few months I’ve been using NodeJS, mainly for a console based app. I must admit it’s not useless and hyped as I thought. I do try to keep away from needless dependencies from its package manager NPM. Also something to get used to is that Node (and js) works asynchronously so your code could be executed ‘out of order’.
node
Run your ‘app.js’ with /usr/bin/node app.js
.
Node itself includes useful functions like for making http(s) requests (nodejs.org docs).
It does not have to a be webapp though, creating a cli or gui app is also possible.
Node package manager
NPM (npmjs.org) has the usual functions like ‘search’ and ‘install’ but also lists insecure, unused or deprecated pkgs.
package.json
Here you can name your package and define stop and start scripts.
node_modules
The dreaded modules ("libs") go in this sometimes huge directory, managed by npm. For example ‘fs’ is for filesystem/io functions.
To use/import a module, add to top of your app: const fs = require('fs')
Another interesting module is ‘pm2’, a process manager which can be used to manage running your app including logging and monitoring (pm2.keymetrics.io).
Variables
- Global scope:
var
- Local:
let
- Constant:
const
Output text to console:
let var1 = "World"
console.log('Hello', var1)
console.log(`Hello ${var1}`) // this is a 'template literal'
JSON
Of course it is ‘supported’ as well as can be, which is nice :)
var jObj = {
“Foo”: "bar",
"Another Key": "Value",
}
add property
jObj['first name'] = 'John'
jObj.firstname = 'John'
convert
- string to obj:
JSON.parse(string)
- stringify obj:
JSON.stringify(obj)
Functions
'func(args) { ... }'
Maybe unusual is that you can use functions with another function as argument.
Arrow notation:
function() {}
becomes() => {}
function(a) {}
becomesa => {}
And there’s…
- callbacks
- promises
- async and wait (syntactic sugar over promises)
(in order from ‘old’ to ‘current’)
These pages helped me better understand these concepts: