Why Gemfury? Push, build, and install  RubyGems npm packages Python packages Maven artifacts PHP packages Go Modules Debian packages RPM packages NuGet packages

Repository URL to install this package:

Details    
@skava/modules / ___dist / persistance / server / readwrite.js
Size: Mime:
"use strict";

/**
 * @file https://github.com/simonlast/node-persist
 */
const _require = require('path'),
      sep = _require.sep;

const _require2 = require('fs'),
      readFileSync = _require2.readFileSync,
      writeFileSync = _require2.writeFileSync,
      existsSync = _require2.existsSync;

const mkdirp = require('mkdirp');

const _require3 = require("../../chain-able/index.js"),
      stringify = _require3.stringify;
/**
 * @tutorial https://shapeshed.com/writing-cross-platform-node/
 * @description path separator for any platform
 * @type {Path.sep | '\\' | '/'}
 */


const separator = sep;
/**
 * @tutorial http://stackabuse.com/read-files-with-node-js/
 * @param {String} absolutePath path to read from
 */

function read(absolutePath) {
  makePathIfNeeded(absolutePath);
  return readFileSync(absolutePath, 'utf8');
}
/**
 * @param {*} json
 * @return {boolean | *}
 */


function tryJSON(json) {
  try {
    const parsed = JSON.parse(json);
    return parsed;
  } catch (parseError) {
    return false;
  }
}
/**
 * @param {any} absolutePath
 * @param {Object | *} [fallback={}]
 * @return {Object | *} parsed json or fallback object
 */


function readJSON(absolutePath, fallback = {
  readfailed: true
}) {
  return tryJSON(read(absolutePath)) || fallback;
}
/**
 * @description split file into [directory, filename]
 *              check if directory exists
 *              mkdirp creates path compat
 *              fs always can create a single file, but not a dir
 *
 * @param {String} absolutePath
 * @return {Boolean} true if it had to create it, false if not
 */


function makePathIfNeeded(absolutePath) {
  // get the final dir excluding the file
  let finalOutputDir = absolutePath.split(separator);
  finalOutputDir.pop();
  finalOutputDir = finalOutputDir.join(separator); // make the final dir if it does not exist

  if (existsSync(finalOutputDir) === false) {
    mkdirp.sync(finalOutputDir);
    return true;
  }

  return false;
}
/**
 * @description write contents to a path
 * @param {String} absolutePath path to write content to
 * @param {String | Object | Array | *} content serializes content to write to file
 * @return {Boolean} wrote successfully
 */


function write(absolutePath, content) {
  let contents = content; // if !isPrimitive?

  if (typeof contents !== 'string') {
    contents = stringify(content);
  }

  makePathIfNeeded(absolutePath);
  return writeFileSync(absolutePath, contents, 'utf8');
}

read.json = readJSON;
const exists = existsSync;
module.exports = {
  read,
  write,
  readJSON,
  exists
};