Node.JS Cheat-sheet

Node.JS Cheat-sheet

Encode String to Base64

console.log(Buffer.from('This message will be encoded to base64', 'utf8').toString('base64')); 

Decode String from Base64

console.log(Buffer.from('VGhpcyBtZXNzYWdlIHdpbGwgYmUgZW5jb2RlZCB0byBiYXNlNjQ=', 'base64').toString('utf8'));

Generate random UUID from console (oneliner)

console.log(require('crypto').randomUUID());

Replace all ocurrences of a string (Method 1)

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

Replace all ocurrences of a string (Method 2)

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

Get date as ISO string

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

Clone / Copy JSON object

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

Clone / Copy Object

let newObject = Object.create(oldObject);

List object keys

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

Make a pause/sleep in the code (Method 1)

async function main(){
	console.log(new Date().toISOString());
	await new Promise(resolve => setTimeout(resolve, 2000)); // Number of milliseconds to wait
	console.log(new Date().toISOString());
}

main();

Make a pause/sleep in the code (Method 2)

function sleep(milliseconds) {
    return new Promise(res => setTimeout(res, milliseconds))
}

async function main() {

    console.log("Before sleep");
    await sleep(20);
    console.log("After sleep");
}

main();

Read character from console (Asynchronous)

const readline = require('readline').createInterface({
  input: process.stdin,
  output: process.stdout
});

readline.question('Enter a value: ', (input) => {
  // Process the input here
  console.log(`You entered: ${input}`);
  readline.close();
});

Read character from console (Synchronous)

const readline = require("readline").createInterface({
    input: process.stdin,
    output: process.stdout,
});

async function getUserInput() {
    return new Promise((resolve) => {
        readline.question("Enter a value: ", (input) => {
            readline.close();
            resolve(input);
        });
    });
}

async function main() {
    try {
        console.log("BEGIN");

        const input = await getUserInput();
        console.log(`You entered: ${input}`);

        console.log("END");
        // Process the input here
    } catch (error) {
        console.error("Error reading input:", error);
    }
}

main();