Node.
js
Cheat Sheet
presented by
Install and use Node.js via nvm
Please note: Only works on macOS, Linux and Windows
Subsystem for Linux (WSL)
# install nvm (Node.js Version Manager)
$ curl -o- https://raw.githubusercontent.com/nvm-sh/nvm/
v0.38.0/install.sh | bash
# install a specific version
$ nvm install 14.17.0
# change the installed version
$ nvm use 14.17.0
# set a specific version as standard
$ nvm alias default 14.17.0
# set a version branch as standard
$ nvm alias default 14
Start an HTTP Server
'use strict';
const http = require('http');
const server = http.createServer((req, res) => {
res.writeHead(200, {
'content-type': 'text/html'
});
res.write('<h1>Hello HTTP!</h1>');
res.end();
});
server.listen(3000);
Start an HTTPS Server
'use strict';
const fs = require('fs');
const https = require('https');
const path = require('path');
const privateKey = fs.readFileSync(
path.join(__dirname, 'privateKey.pem')
);
const certificate = fs.readFileSync(
path.join(__dirname, 'certificate.pem')
);
const server = https.createServer({
key: privateKey,
cert: certificate
}, (req, res) => {
res.writeHead(200, {
'content-type': 'text/html'
});
res.write('<h1>Hello HTTPS!</h1>');
res.end();
});
server.listen(3000);
Read and write Files
const fs = require('fs');
const path = require('path');
(async () => {
const hosts = await fs.readFile(
'/etc/hosts',
{ encoding: 'utf8' }
);
console.log(hosts);
await fs.writeFile(
path.join(__dirname, 'localCopy.txt'),
hosts,
{ encoding: 'utf8' }
);
})();
Read and write Files as Streams
const fs = require('fs');
const path = require('path');
const stream = require('stream');
const source = fs.createReadStream('/etc/hosts');
const target = fs.createWriteStream(path.join(__dirname,
'localCopy.txt'));
stream.pipeline(source, target, err => {
if (err) {
// ...
}
// ...
});
Provide an HTTP API with Express
On CLI:
$ npm install body-parser cors express
In Node.js:
'use strict';
const bodyParser = require('body-parser');
const cors = require('cors');
const express = require('express');
const http = require('http');
const app = express();
app.use(cors());
app.use(bodyParser.json());
app.get('/', (req, res) => {
res.json({ text: 'Hello JSON!' });
});
app.post('/', (req, res) => {
console.log(req.body);
res.status(200).end();
});
const server = http.createServer(app);
server.listen(3000);
Set up Logging
On CLI:
$ npm install flaschenpost
In Node.js:
'use strict';
const { flaschenpost } = require('flaschenpost');
const http = require('http');
const logger = flaschenpost.getLogger();
const server = http.createServer((req, res) => {
res.write('<h1>Hello HTTP!</h1>');
res.end();
});
const port = 3000;
server.listen(port, () => {
logger.info('Server started ...', { port });
});
Read Environment Variables
On CLI:
$ npm install processenv
In Node.js:
'use strict';
const { processenv } = require('processenv');
const http = require('http');
const server = http.createServer((req, res) => {
res.write('<h1>Hello HTTP!</h1>');
res.end();
});
const port = processenv('PORT', 3000);
server.listen(port);
Compute Hash
'use strict';
const crypto = require('crypto');
const hashAlgorithm = crypto.createHash('sha256');
hashAlgorithm.update('the native web');
const hash = hashAlgorithm.digest('hex');
console.log(hash);
Encrypt Text
'use strict';
const crypto = require('crypto');
const plainText = 'the native web';
const password = 'secret';
const salt = crypto.randomBytes(256);
const key = crypto.pbkdf2Sync(password, salt, 10000, 32,
'sha256');
const iv = crypto.randomBytes(16);
const encryptionAlgorithm = crypto.createCipheriv('aes-256-cbc',
key, iv);
let cipherText = encryptionAlgorithm.update(plainText, 'utf8', 'hex');
cipherText += encryptionAlgorithm.final('hex');
console.log(cipherText);
Decrypt Text
Please note: key, iv und cipherText need to be the same as
those that were used for encryption.
const decryptionAlgorithm = crypto.createDecipheriv('aes-256-cbc',
key, iv);
let resultingText = decryptionAlgorithm.update(cipherText, 'hex',
'utf8');
resultingText += decryptionAlgorithm.final('utf8');
console.log(resultingText);
Create an UUID
Requires Node.js 15.6.0 or later
'use strict';
const crypto = require('crypto');
const uuid = crypto.randomUUID();
Output System Usage
'use strict';
const { arch, platform, version, pid } = process;
const { userCPUTime, systemCPUTime, maxRSS, fsRead, fsWrite }
= process.resourceUsage();
const { rss, heapTotal, heapUsed, external } = process.
memoryUsage();
const uptime = process.uptime();
console.log({
host: { architecture: arch, platform },
node: { version },
process: { id: pid, uptime },
cpuUsage: { user: userCPUTime, system: systemCPUTime },
memoryUsage: { rss, maxRss: maxRSS, heapTotal, heapUsed,
external },
diskUsage: { read: fsRead, write: fsWrite }
});
Structure the package.json
{
"name": "your-module",
"version": "1.0.0",
"description": "your-module does ...",
"contributors": [
{
"name": "Jane Doe",
"email": "
[email protected]"
}
],
"main": "build/lib/your-module.js",
"types": "build/lib/your-module.d.ts",
"dependencies": {
// ...
},
"devDependencies": {
// ...
},
"scripts": {
// ...
},
"repository": {
"type": "git",
"url": "git://github.com/..."
},
"keywords": [
// ...
],
"license": "MIT"
}
Set up Mocha
Install on CLI:
$ npm install assertthat mocha
In Node.js:
'use strict';
const { assert } = require('assertthat');
suite('add', () => {
test('returns the sum of two numbers.', async () => {
const left = 23;
const right = 42;
const actual = add(left, right);
const expected = 65;
assert.that(actual).is.equalTo(expected);
});
});
Call on CLI:
$ npx mocha --async-only --bail --recursive --ui tdd
Configure ESLint
On CLI:
$ npm install eslint eslint-config-es
In .eslintrc.json:
{
"extends": "es/node"
}
Configure TypeScript
On CLI:
$ npm install typescript ts-node
In tsconfig.json
{
"compilerOptions": {
"baseUrl": ".",
"declaration": true,
© Oleksii Lishchyshyn/Shutterstock.com, © Bill81/Shutterstock.com
© Josep.Ng/Shutterstock.com, © Darko Petrovic/Shutterstock.com,
"esModuleInterop": true,
"lib": [ "esnext" ],
"module": "commonjs",
"outDir": "build",
"resolveJsonModule": true,
"strict": true,
"target": "es2019"
},
"include": [
"./**/*.ts"
]
}
Golo Roden is founder and CTO of the native
web GmbH. He advises companies on technol-
ogies and architecture in web and cloud envi-
ronments, including topics such as TypeScript,
Node.js, React, CQRS, event-sourcing and do-
main-driven design (DDD).
www.thenativeweb.io
javascript-conference.com