Repository URL to install this package:
|
Version:
1.2.8 ▾
|
"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
/**
* @file https://github.com/simonlast/node-persist
*/
const path_1 = require("path");
const fs_1 = require("fs");
const mkdirp_1 = __importDefault(require("mkdirp"));
// import { stringify } from 'chain-able'
const stringify_1 = require("../../deps/stringify");
/**
* @tutorial https://shapeshed.com/writing-cross-platform-node/
* @description path separator for any platform
* @type {Path.sep | '\\' | '/'}
*/
const separator = path_1.sep;
/**
* @tutorial http://stackabuse.com/read-files-with-node-js/
* @param {String} absolutePath path to read from
*/
function read(absolutePath) {
makePathIfNeeded(absolutePath);
return fs_1.readFileSync(absolutePath, 'utf8');
}
exports.read = read;
/**
* @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;
}
exports.readJSON = readJSON;
/**
* @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
*
* @return 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 (fs_1.existsSync(finalOutputDir) === false) {
mkdirp_1.default.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_1.stringify(content);
}
makePathIfNeeded(absolutePath);
return fs_1.writeFileSync(absolutePath, contents, 'utf8');
}
exports.write = write;
read.json = readJSON;
const exists = fs_1.existsSync;
exports.exists = exists;
//# sourceMappingURL=readwrite.js.map