Authorization

js Node.js
// curl -u toto:password http://localhost:8000/
require('http').createServer((req, res) => {
  if (req.headers.authorization) {
    res.write(req.headers.authorization + "\n");
    let userPass = Buffer
      .from(req.headers.authorization.match(/Basic\s(.*)/i)[1], 'base64')
      .toString('ascii')
      .match(/(.*):(.*)/i);
    res.write(userPass[0] + "\n");
    res.write(userPass[1] + "\n");
    res.write(userPass[2] + "\n");
    res.end();
  } else {
    res.setHeader("WWW-Authenticate", "Basic realm=\"Authorization Required\", charset=\"UTF-8\"");
    res.writeHead(401, { 'Content-Type': 'application/json' });
    res.end('{ msg: "Authorization Required" }');
  }
}).listen(8000);
Basic dG90bzpwYXNzd29yZA==
toto:password
toto
password

Get process stats with nodejs

js Node.js
let child_process = require("child_process");

let PID = 6991;

child_process.exec("ps --pid " + PID + " -o %cpu,rss,vsz,%mem", (error, stdout, stderr) => {
  // prepare data before send
  let txt = stdout.replace(/\n$/i, "").split("\n"); // remove the last \n and split by \n
  let lbltxt = txt[0].split(/\s+/g); // split by change space chars
  let datatxt = txt[1].replace(/^\s+/g, "").split(/\s+/g); // remove the first space chars and split by space chars
  console.log(stdout);
  console.log(txt);
  console.log(lbltxt);
  console.log(datatxt);
  let psinfo = {};
  for (let i = 0; i < lbltxt.length; i++) {
    console.log(i + " " + lbltxt[i] + " " + datatxt[i]);
    psinfo[lbltxt[i]] = datatxt[i];
  }
  console.log(psinfo);
});
// infos

Webcam with Node.js

js Node.js
// install with npm node-webcam
let NodeWebcam = require( "node-webcam" );
let fs = require("fs");

let opts1 = {
    width: 1280,
    height: 720,
    quality: 100,
    delay: 0,
    saveShots: false,
    output: "jpeg",
    device: false,
    verbose: false,
    callbackReturn: "base64"
};

NodeWebcam.capture( "test_picture", opts1, function( err, data ) {
    let imagehtml = "<img src='" + data + "'>";
    fs.writeFile("image.html", imagehtml, (err) => { if(err) throw err });
});

Signal and close in Node.js

js Node.js
// Disale program close
process.stdin.resume()
process.on("exit", () => console.log("oui"));

// Catches ctrl+c signal
process.on("SIGINT", () => process.exit(130));
// Cathes signals
process.on("SIGUSR1", () => process.exit());
process.on("SIGUSR2", () => process.exit());

// Cathes uncaughtException
process.on("uncaughtException", () => process.exit(1));