UNPKG

1.49 kBJavaScriptView Raw
1'use strict';
2
3/**
4 * promiseUtil.js is a small library that promisifies the following:
5 * - https library
6 * - child_process library
7 *
8 * so we don't have to import yet another external NPM dependencies
9 *
10 * ref: [https] https: //www.tomas-dvorak.cz/posts/nodejs-request-without-dependencies/
11 * ref: [child_process] https: //gist.github.com/miguelmota/e8fda506b764671745852c940cac4adb
12 */
13
14// Dependencies
15const util = require('util');
16const execChildProcess = require('child_process').exec;
17const spawnChildProcess = require('child_process').spawn;
18
19/*
20 * Fetch from a given url
21 * @params
22 * url: String
23 *
24 * example: fetch(url)
25 */
26module.exports.fetch = function (url) {
27 return new Promise((resolve, reject) => {
28 const lib = url.startsWith('https') ? require('https') : require('http');
29 const request = lib.get(url, response => {
30 if (response.statusCode < 200 || response.statusCode > 299) {
31 reject(new Error('Failed to load page, status code: ' + response.statusCode));
32 }
33 const body = [];
34 response.on('data', chunk => body.push(chunk));
35 response.on('end', () => resolve(body.join('')));
36 });
37 request.on('error', err => reject(err));
38 });
39};
40
41/*
42 * Execute cli command
43 * @params
44 * cmd: String
45 *
46 * example: exec(cmd);
47 */
48module.exports.exec = util.promisify(execChildProcess);
49
50/*
51 * Spawn cli command
52 * @params
53 * cmd: String
54 *
55 * example: spawn(cmd);
56 */
57module.exports.spawn = util.promisify(spawnChildProcess);
\No newline at end of file