#technology #reference-sheet #cheat-sheet #nodejs
idea
This is a reference sheet on NodeJS
Networking
Making requests:
const https = require('https')
const options = {
hostname: 'encrypted.google.com',
port: 443,
path: '/',
method: 'GET'
}
const req = https.request(options, (res) => {
console.log('statusCode:', res.statusCode)
console.log('headers:', res.headers)
res.on('data', (d) => {
process.stdout.write(d)
})
res.on('end', () => {
// finished receiving data
})
})
req.on('error', (e) => {
console.error(e)
});
// For POST:
//
// req.write(data)
req.end()
Using fetch (npm install --save node-fetch)
const fetch = require("node-fetch")
fetch("url", {
headers: {
},
"method": "GET",
"body": null,
// "referrer": "",
// "referrerPolicy": "strict-origin-when-cross-origin",
// "mode": "cors"
})
Parsing urls[1]:
const url = require('url')
// Assuming a request object
// Assuming url http://localhost:8080/app.js?foo=bad&baz=foo
const queryObject = url.parse(req.url,true)
url.parse(req.url,true).query // { foo: 'bad', baz: 'foo' }
url.parse(req.url,true).host // 'localhost:8080'
url.parse(req.url,true).pathname // '/app.js'
url.parse(req.url,true).search // '?foo=bad&baz=foo'
Simple server:
const http = require('http');
const server = http.createServer(function(req, res) {
res.writeHead(200, {'Content-Type': 'text/plain'});
res.end("It woerks.");
});
server.listen();
Watch
Use npm-watch [^3]
npm install npm-watch --save-dev
In package.json:
"watch": {
"test": {
"patterns": [
"src",
"test"
],
"extensions": "js"
}
},
//...
"scripts": {
//...
"watch": "npm-watch",
//...
}