const logger = require('./logger.js'); const realpath = require('fs/promises').realpath; const stat = require('fs/promises').stat; const http = require('http'); const { HTTP_GET, HTTP_POST } = require('./constants.js'); function timeDiff(startTime) { if (startTime instanceof Date) { return (new Date().getTime() - startTime.getTime()); } return new Date().getTime - startTime; } function clone(object) { var clone = {}; for (key in object) { clone[key] = object[key]; } return clone; } function httpGET(host, port, path, args) { return httpRequest(host, port, path, HTTP_GET, args); } function httpPOST(host, port, path, args) { return httpRequest(host, port, path, HTTP_POST, args); } function httpRequest(host, port, path, method, args) { return new Promise(function (resolve, reject) { if (!path.startsWith("/")) { path = "/" + path; } logger.debug('sending http \'' + method + '\' request to \'' + host + ':' + port + path + '\'...'); const request = http.request({ hostname: host, port: port, path: path, method: method }, function (response) { if (!response) { return reject('error: no response from host for http \'' + method + '\' request \'' + host + ':' + port + path + '\''); } var responseData = ""; response.on('data', function (data) { responseData += data; }); response.on('end', function () { logger.debug('http \'' + method + '\' request \'' + host + ':' + port + path + '\' returned status code \'' + response.statusCode + '\' and data \'' + responseData + '\''); var fn = resolve; if (response.statusCode != 200) { fn = reject; } if (!responseData) { return fn(); } try { return fn(JSON.parse(responseData)); } catch (err) { return fn(responseData); } }); }); request.on('error', function (err) { return reject('http \'' + method + '\' request \'' + host + ':' + port + path + '\' returned an error >>> ' + err); }); request.end(); }); } function toHex(value) { var hex = Number(value).toString(16); return hex; } function sortById(array) { return array.sort(function (a, b) { return a.id - b.id; }); } function fileExists(file) { return new Promise((resolve, reject) => { if (file == undefined) { reject('can not check the existence of an undefined file'); } resolvePath(file) .then((path) => { stat(path) .then((stats) => { resolve({path, stats}); }) }) .catch(reject); }); } function resolvePath(file) { return new Promise((resolve, reject) => { if (file == undefined) { reject('can not resolve a path to an undefined file'); } realpath(file) .then(resolve) .catch((err) => { reject('resolving path \'' + file + '\' encountered an error >>> ' + err); }); }); } module.exports = { timeDiff, clone, httpGET, httpPOST, toHex, sortById, fileExists, resolvePath }