Node.JS Lab

G3N3R4T1NG.C0D3.4.FUN!


Quick reference of useful Linux commandsand much more. The kind of thing you need handy when emergencies arise.

NATO Phonetic Alphabet

NATO_Phonetic_Alphabet

Linux permissions

Linux_permissions

List contents of .tgz file

tar tf /home/user/my_file.tgz

Compress folder into a .tgz file

tar cvzf /home/user/my_folder.tgz my_folder

Compress folder into a .tgz file with date

tar cvzf /home/user/my_folder_$(date +%d-%m-%Y_%H-%M-%S).tgz my_folder

Uncompress .tgz file into a folder

tar xzvf my_folder.tgz -C /home/user/my_folder

SSH Copy file (local > remote) (Upload)

scp my_file.tgz user@host:/home/user/my_file.tgz

SSH Copy file (remote > local) (Download)

scp user@host:/home/user/my_file.tgz my_file.tgz

SSH Copy directory (local > remote) (Upload)

scp -r /home/source user@host:/home/user/destination

SSH Copy directory (remote > local) (Download)

scp -r user@host:/home/user/source /home/destination

Check Linux distro and version

lsb_release -a

Follow journal and grep something

journalctl -f | grep something

Follow journal and grep several things

journalctl -f | grep -e orange -e peach -e raspberry

Follow journal and grep regex

journalctl -f | egrep '(orange|peach|raspberry)'

Clear console, restart a service, follow journal, and grep regex

clear && clear && systemctl restart my_service && journalctl -f | egrep '(something)'

Unzip into a specific folder

unzip my_file.zip -d my_folder

Find string in files

grep -r "string to find" /home/dir/*.ext

Find a file

find /home/user/ -name file_name.ext

MongoDB - Connection string for replica set

mongodb://db1.server.com:port,db2.server.com:port,arbiter.server.com:port/MyDataBaseName?replicaSet=MyReplicaSetName

MongoDB - updateOne() example

db.collection_name.updateOne(
    {
        _id: ObjectId("UUIDOFTHEOBJECT")
    } , {
        $set: {
            field1: {
                field2: "new value",
                field3: 3,
                field4: {
                    field5: false
                }
            }
        }
    }
);

Node.JS - Replace all ocurrences of a string (Method 1)

"hello.user.test".split(".").join(" ");

Node.JS - Replace all ocurrences of a string (Method 2)

"hello_user_test".replace(/_/g, " ");

Node.JS - Get date as ISO string

(new Date(Date.now())).toISOString();

Node.JS - Clone / Copy JSON object

let oldObject = { "website":"www.nodejslab.com" };
let newObject = {};
newObject = Object.assign(newObject, oldObject);

Certbot - Generate SSL/TLS certificates for NGINX

certbot --nginx -d example.com -d example.net

Certbot - Renew SSL/TLS certificates for NGINX

(TO DO: info here: https://certbot.eff.org/docs/using.html)
certbot renew
certbot --force-renew

Node.JS - List object keys

console.log(Object.keys(myJsonObj));

See file sizes inside a given folder

du /home/* -sh

See size of current folder

du -sch

See size of file system

df -h

Docker - pull image from https://hub.docker.com

docker pull imageName
docker pull imageName:latest
docker pull imageName:1.2.3

Docker - Follow container logs

docker logs -f --since 1m containerNameOrID

Docker - Go inside the container

docker exec -it containerNameOrID /bin/bash

Docker - See images in local PC

docker images

Docker - See runnning containers

docker ps

Docker - Stop a container

docker stop containerNameOrID

Docker - Build an image

docker build . -t myImageName

Docker - Delete an image by force

docker image rm --force myImageNameOrID

Docker - Inspect the layers of an image

docker history --human --format "{{.CreatedBy}}: {{.Size}}" myImageNameOrID

Docker - Run an image in a container in detached mode

docker run -p LocalPort:InternalPort -d myImageNameOrID

Docker - Run an image in a container in detached mode in the host network

docker run -p LocalPort:InternalPort -d myImageNameOrID --network host

Docker - Run an image in a named container and accessing the instance from the host without the container's IP

docker run -d --name newContainerName -e url=http://localhost:externalAppPort -p externalAppPort:internalAppPort imageName
Example:
docker run -d --name some-ghost -e url=http://localhost:3001 -p 3001:2368 ghost

Docker - containers location

/var/lib/docker/containers

Modify user password

passwd userName

Add user

adduser newUserName

Add user to SUDO group

usermod -aG sudo userName

CURL to display total time

curl --request GET 'https://www.somewhere.com' --write-out '\nTOTAL TIME: %{time_total} seconds'

CURL to POST body from JSON file

curl --request POST 'https://www.example.com' -d @MyJSONFile.json --header "Content-Type: application/json"

Node.JS - short and simple string encryption / decryption with AES-256

// Libraries
const crypto = require('crypto');

// Constants
const OUTPUT_FORMAT = "hex";
const ALGORITHM = "aes256";
const KEY = "012345ABCDEFGHIJKLMNOPQRSTUVWXYZ";
const IV = "ABCDEF0123456789";

// Implementations
function encrypt(message) {
    let cipher = crypto.createCipheriv(
        ALGORITHM, 
        Buffer.from(KEY), 
        Buffer.from(IV)
    );
    return (Buffer.concat([
        cipher.update(message), 
        cipher.final()
    ])).toString(OUTPUT_FORMAT);
}

function decrypt(message) {
    let decipher = crypto.createDecipheriv(
        ALGORITHM, 
        Buffer.from(KEY), 
        Buffer.from(IV)
    );
    return (Buffer.concat([
        decipher.update(Buffer.from(message, OUTPUT_FORMAT)),
        decipher.final()
    ])).toString('utf8');
}

// Program
console.log(encrypt("Hello"));
console.log(decrypt(encrypt("Hello")));

Grep .gz log files

zgrep 'StringIASearchingFor' logFileName.gz

Docker - execute command inside container (check Node.JS version inside container)

docker exec myContainerID node --version

Node.JS - generate UUID-like strings with crypto

const crypto = require('crypto');
let uuidStyleStr = crypto.randomBytes(4).toString('hex') + "-" +
    crypto.randomBytes(2).toString('hex') + "-" +
    crypto.randomBytes(2).toString('hex') + "-" +
    crypto.randomBytes(2).toString('hex') + "-" +
    crypto.randomBytes(6).toString('hex');
console.log(uuidStyleStr);

Check OS version

lsb_release -a

Node.JS - scramble strings N times

let myStr = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789abcdefghijklmnopqrstuvwxyz\\\"";

function scramble(str, times) {

    str = Buffer.from(str, 'utf8');

    console.log(str + " >>>----> " + str.length + " chars");

    for (let i = 1; i <= times; i++) {

        let orig = Math.floor(Math.random() * str.length);
        let dest = Math.floor(Math.random() * str.length);

        let temp = str[orig];
        str[orig] = str[dest];
        str[dest] = temp;

    }

    console.log(str + " >>>----> " + str.length + " chars");
}

scramble(myStr, 223);

/* 
    Expected output (mileage may vary):
    ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789abcdefghijklmnopqrstuvwxyz\" >>>----> 64 chars
    4RjeE6DzBtYGAFTrbymnxIZXNq9c0kV"sUWhPiLKg\avJfSHl72p385uCwOdQM1o >>>----> 64 chars
*/