UNPKG

@blaasvaer/frmwrk

Version:

My personal Node framework

85 lines (76 loc) 2.04 kB
/** * This is a utility class for the frmwrk framework. */ var fs = require('fs'); class Utils { constructor () {} /** * Read a directory asyncronously * @param {string} dirname The name of the directory to read from. * @return {Promise} A Promise. * @author Sam Blåsvær <sam@blaasvaer.dk> */ readdirAsync ( dirname ) { // console.log("Dirname", dirname); return new Promise(function( resolve, reject ) { fs.readdir( dirname, function( err, filenames ) { if ( err ) reject( err ); else resolve( filenames ); }); }); } /** * Read a file asyncronously * @param {string} filename The name of the fiel to read. * @param {string} encoding The type of encoding to use when readig the file. * @return {Promise} A Promise. * @author Sam Blåsvær <sam@blaasvaer.dk> */ readFileAsync ( filename, encoding ) { return new Promise(function( resolve, reject ) { fs.readFile(filename, encoding, function( err, data ) { if ( err ) reject( err ); else resolve( data ); }); }); } /** * Get a file (passing on to async) * @param {string} filename The name of the file to read. * @return {Promise} A Promise. */ getFile ( filename ) { // console.log("getFile filename", filename); return this.readFileAsync( filename, 'utf8' ); } /** * Delay a promise for debugging * @return {Function} A function returning a Promise. */ sleep ( ms ) { return function( x ) { return new Promise( resolve => setTimeout( () => resolve( x ), ms ) ); }; } /** * Removes all trailing slashes from URL * @param {string} url * @return {string} Return the string without trailing slashes. */ removeTrailingSlashes( url ) { return url.replace(/\/+$/, ''); } /** * Removes all starting and trailing slashes from URL * @param {string} url * @return {string} Return the string without trailing slashes. */ removeStartingTrailingSlashes( url ) { return url.replace(/^\/+|\/+$/g, '') } } module.exports = new Utils();