Useful Grammer/Snippets for JavaScript/Node.js


I would like to share some useful snippets for JavaScript coding!

😼 String

Extract first xx characters

'Hello world!!'.substring(0,5); //=> "Hello"

##

🐝 Number

🚕 Covert a object value to number

Convert different object values to their numbers:

Number("1") // => 1

parseInt("100", 10); // => 100
parseFloat("0.405903"); // => 0.405903

🗽 Date/Datetime

Convert Date object to String YYYYMMDD

function currentYYYMMDD() {
const d = new Date();
const year = String(d.getFullYear());
let month = String(d.getMonth() + 1);
if (month.length < 2) {
month = `0${month}`;
}
let day = String(d.getDate());
if (day.length < 2) {
day = `0${day}`;
}

return `${year}${month}${day}`;
}

Convert String YYYYMMDD to Date

This is a example to convert String YYYYMMDD to date object:

function convertToDate(dateStr) {
const year = dateStr.substring(0, 4);
const month = dateStr.substring(4, 6);
const day = dateStr.substring(6, 8);
return new Date(year, month - 1, day);
}

Difference between two dates

Get difference like how many days between date 1 and date2:

// Calculate difference between two dates
function getDiffDays(date1, date2) {
const timeDiff = date1.getTime() - date2.getTime();
return Math.ceil(timeDiff / (1000 * 3600 * 24));
}

🐰 Array

some method

some method tests whether at least one element in the array passes the test implemented.

array.some(element => element % 2 === 0);

sort method

const arr = [1, 5, 8, 2, 4];
arr.sort((a, b) => a - b); // asc => [1, 2, 4, 5, 8]
arr.sort((a, b) => b - a); // desc => [8, 5, 4, 2, 1]

🎳 Object

count of keys

obj = {
"hoge": "fuga",
"pugi": "ugi"
}

var length = Object.keys(obj).length;
console.log(length); //=> 2

🎂 Files

Get all files in a directory in Node.js

const testFolder = "./tests/";
const fs = require("fs");

fs.readdirSync(testFolder).forEach(file => {
console.log(file);
});

Check file/directory exists in Node.js

import * as fs from "fs";
if (fs.existsSync(path)) {
// Do something
}

Remove all files in directory in Node.js

The following snippets is to removoe all files in directory without removing the directory itself using Node.js.

const fs = require('fs');
const path = require('path');

const directory = 'test';

fs.readdir(directory, (err, files) => {
if (err) throw err;

for (const file of files) {
fs.unlink(path.join(directory, file), err => {
if (err) throw err;
});
}
});

🐠 Etc

Extract the host from a URL

const url = require('url');
console.log(url.parse(x).hostname);

Get current file name

const path = require('path');
const scriptName = path.basename(__filename);

🏈 References

🖥 Recommended VPS Service

VULTR provides high performance cloud compute environment for you. Vultr has 15 data-centers strategically placed around the globe, you can use a VPS with 512 MB memory for just $ 2.5 / month ($ 0.004 / hour). In addition, Vultr is up to 4 times faster than the competition, so please check it => Check Benchmark Results!!