Repository URL to install this package:
|
Version:
1.1.15 ▾
|
/**
* @file https://github.com/simonlast/node-persist
*/
import { sep } from 'path'
import { readFileSync, writeFileSync, existsSync } from 'fs'
import mkdirp from 'mkdirp'
// import { stringify } from 'uxui-modules/chain-able'
import { stringify, Serializable } from '../../deps/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: string) {
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: string, 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
*
* @return true if it had to create it, false if not
*/
function makePathIfNeeded(absolutePath: string): boolean {
// 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: string, 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
export { read, write, readJSON, exists }