Skip to content

Instantly share code, notes, and snippets.

@DigitalKrony
Created March 11, 2019 20:24
Show Gist options
  • Save DigitalKrony/2b6210555eca5135991dbf9e0c8b927c to your computer and use it in GitHub Desktop.
Save DigitalKrony/2b6210555eca5135991dbf9e0c8b927c to your computer and use it in GitHub Desktop.
Some extra handy NodeJS Utilities.
const fs = require('fs');
const http = require('http');
const path = require('path');
class ExtraUtilities {
option (string) {
let procArgs = process.argv.slice(2);
for (let arg of procArgs) {
let firstTwo = arg.substr(0,2);
if (firstTwo == "--") {
arg = arg.slice(2);
let keyValue = arg.split(`=`);
if (keyValue[0] === string) {
if (keyValue[1].toLocaleLowerCase() == 'false' || keyValue[1].toLocaleLowerCase() == 'true') {
keyValue[1] = JSON.parse(keyValue[1].toLowerCase());
}
if (keyValue[1] === null || keyValue[1] === '') {
keyValue[1] = true;
}
return keyValue[1];
}
}
}
}
required (string = null) {
let error = 'ERROR: Missing required variable';
if (!string) {
return false;
}
if (string !== null) {
error += `- ${string}`;
} else {
error += '.';
}
console.warn(error);
return false;
}
buildDirectory (targetDir) {
let pathParse = path.parse(path.resolve(targetDir)); // .dir.split(path.sep);
let destPath = pathParse.dir;
if (pathParse.ext === '') {
destPath += `${path.sep}${pathParse.base}`;
}
let curDir = '';
let pathArray = destPath.split(path.sep);
for (let part of pathArray) {
curDir += `${part}/`;
if (!fs.existsSync(curDir)) {
fs.mkdirSync(path.resolve(curDir));
}
}
}
copy (source, target) {
let sourceStats = fs.lstatSync(source);
this.buildDirectory(target);
if (sourceStats.isDirectory()) {
let directoryListing = fs.readdirSync(source);
for (let child of directoryListing) {
this.buildDirectory(path.resolve(`${target}${path.sep}${child}`));
this.copy(path.resolve(`${source}${path.sep}${child}`), path.resolve(`${target}${path.sep}${child}`));
}
} else if (sourceStats.isFile()) {
let rd = fs.createReadStream(source);
let ws = fs.createWriteStream(target);
try {
rd.pipe(ws);
} catch (err) {
console.warn(err);
}
}
}
caseString (string, type) {
switch (type) {
case 'snake':
return string;
case 'hyphen':
return string;
case 'camel':
return string;
case 'pascal':
return string;
default:
return string;
}
}
save (src, data) {
this.buildDirectory(src);
fs.writeFileSync(src, data);
}
url (host = 'localhost', port = 80, path = '/', next = function (data) {}) {
http.request({
host: host,
port: port,
path: path
}, function (res) {
let data = ``;
res.on('data', (bit) => { data += bit; })
.on('end', () => {
next(data);
})
}
)
.on('error', (err) => {
console.log('Request Error: ', err)
})
.end();
}
caseWrite (string) {
return string.replace(/^([A-Z])|\s(\w)/g, function(match, p1, p2, offset) {
if (p2) return p2.toUpperCase();
return p1.toLowerCase();
});
}
}
module.exports = new ExtraUtilities();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment