Home Reference Source Repository

src/utils.js

// Import the neccesary modules.
import childProcess from 'child_process';
import fs from 'fs';
import path from 'path';

import { tempDir } from './config/constants';
import { name } from '../package.json';

/**
 * Removes all the files in the temporary directory.
 * @param {String} [tmpPath=beerio-api/tmp] - The path to remove all the files within (Default is set in the `config/constants.js`).
 * @returns {void}
 */
function _resetTemp(tmpPath = tempDir) {
  const files = fs.readdirSync(tmpPath);
  files.forEach(file => {
    const stats = fs.statSync(path.join(tmpPath, file));
    if (stats.isDirectory()) {
      _resetTemp(file);
    } else if (stats.isFile()) {
      fs.unlinkSync(path.join(tmpPath, file));
    }
  });
}

/**
* Create the temporary directory.
* @returns {void}
*/
export function createTemp() {
  if (!fs.existsSync(tempDir)) fs.mkdirSync(tempDir);
  if (fs.existsSync(tempDir)) _resetTemp();
}

/**
 * Reset the default log file.
 * @returns {void}
 */
export function resetLog() {
  const logFile = path.join(tempDir, `${name}.log`);
  if (fs.existsSync(logFile)) fs.unlinkSync(logFile);
}

/**
 * Execute a command from within the root folder.
 * @param {String} cmd - The command to execute.
 * @returns {Promise} - The output of the command.
 */
export function executeCommand(cmd) {
  return new Promise((resolve, reject) => {
    childProcess.exec(cmd, {
      cwd: __dirname
    }, (err, stdout) => {
      if (err) return reject(err);
      return resolve(stdout.split('\n').join(''));
    });
  });
}