Node - auto-mate/CheatSheetWiki GitHub Wiki

NodeJs

Run .js file as

node <filename.js>  

Install package with

npm install <package name>  

Web Server

var http = require('http');

http.createServer(function (req, res) {  
  res.writeHead(200, {'Content-Type': 'text/html'});  
  res.end('Hello World!');  
}).listen(8080);  

Async As Sync

Put everything inside the (async () => { })() format as it returns a promise

// load sql module  
var sql = require('mssql');  
// show a date
console.dir("1"+Date()+"\n");  

// use async and await to make promises wait for completion before continuing  
(async () => {  
    try {                  
        // sql.connect returns promise i.e. await  
        await sql.connect('Server=<>,1433;Database=<>;User Id=<>;Password=<>;TrustServerCertificate=true');  
        // sql.query returns promise i.e. await  
        const result = await sql.query`SELECT TOP 5 * FROM <>`;  
        console.dir(result);  
        sql.close();  
        console.dir("2"+Date()+"\n")  // these may be out of order if outside the ()() format
        console.dir("3"+Date()+"\n")  // these may be out of order if outside the ()() format
    } catch (err) {        
        console.dir(err.name);  
    }  
})()  

Web Server Streaming SQL Server Data

// run as c:\...\node <ThisFileName>    

// load mssql module    
var sql = require('mssql')    

// load http module    
var http = require("http");    

// create server    
http.createServer(function(request, response) {    
    // write http header for streaming/unbuffered data    
	response.writeHead(200, { "Content-Type": "text/event-stream" });    
    // stream data every 2 secs    
    setInterval(    
    function() {     
            // make interval function async to allow syncronise awaits on db promises       
            (async () => {    
                try {    
                // sql.connect is promise hence await    
                const conn = await sql.connect('Server=<>,1433;Database=<>;User Id=<>;Password=<>;TrustServerCertificate=true')    
                // sql.query is promise hence await    
                const result = await sql.query`SELECT TOP 5 * FROM <tableNAme>`    
                
                // loop records    
                for (i=0;i<result.recordset.length;i++) {    
                    // write output and send  
                    response.write(result.recordset[i]['<fieldName>']+"\n")    
                }
                // inefficient close sql but for example only    
                sql.close()    
            } catch (err) {    
                // output any error     
                console.dir(err)    
            }    
            })()    
    // also write date to stream (may be out of sync so put in function ()() )    
    response.write(Date()+"\n")
	}, 2000);    
    // port for server    
}).listen(8080);    

Web Server HTTPS

const https = require("https");    
const fs    = require("fs");    

const options = {    
  key: fs.readFileSync('../certs/private-key.pem'),    
  cert: fs.readFileSync('../certs/certificate.pem'),    
};    

https.createServer(options, (req, res) => {    
  res.writeHead(200);    
  res.end('hello world\n');    
}).listen(8000);    

// generate test certs with     
// openssl req -x509 -newkey rsa:2048 -nodes -sha256 -subj /CN=localhost -keyout private-key.pem -out certificate.pem      
// run using/in "mingw64/bin" in windows    
⚠️ **GitHub.com Fallback** ⚠️