blinky/libs/util.js

59 lines
No EOL
1.5 KiB
JavaScript

const logger = require('./logger.js');
const realpath = require('fs').realpath;
const stat = require('fs').stat;
function exit(err, code) {
if (code === undefined) {
code = 0;
if (err !== undefined) {
code = 1;
}
}
if (err) {
logger.error(err);
logger.error(global.appName + ' ' + global.appVersion + ' ended due to an error');
} else {
logger.info(global.appName + ' ' + global.appVersion + ' shutting down gracefully')
}
process.exit(code);
}
async function fileExists(file) {
if (file === undefined) {
throw new Error('can not check the existence of an undefined file');
}
let path = await resolvePath(file);
return await new Promise((resolve, reject) => {
stat(path, (err, stats) => {
if (err) {
reject(err);
}
resolve({ path, stats });
})
});
}
async function resolvePath(file) {
if (file === undefined) {
throw new Error('can not resolve a path to an undefined file');
}
return await new Promise((resolve, reject) => {
realpath(file, (err, resolvedPath) => {
if (err) {
reject(new Error('resolving path \'' + file + '\' encountered an error >>> ' + err));
}
resolve(resolvedPath);
})
});
}
async function sleep(milliseconds) {
return new Promise(resolve => setTimeout(resolve, milliseconds));
}
module.exports = {
exit,
fileExists,
resolvePath,
sleep
};