Repository URL to install this package:
|
Version:
2.0.2 ▾
|
/**
* @file https://github.com/simonlast/node-persist
*/
import { sep } from 'path'
import { readFileSync, writeFileSync, existsSync } from 'fs'
import { sync } from 'mkdirp'
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')
}
function tryJSON(json: string) {
try {
const parsed = JSON.parse(json)
return parsed
} catch (parseError) {
return false
}
}
/**
* @return 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
const finalOutputDirList = absolutePath.split(separator)
finalOutputDirList.pop()
const finalOutputDir = finalOutputDirList.join(separator)
// make the final dir if it does not exist
if (existsSync(finalOutputDir) === false) {
sync(finalOutputDir)
return true
}
return false
}
/**
* @description write contents to a path
* @param absolutePath path to write content to
* @param content serializes content to write to file
* @return wrote successfully
*/
function write(absolutePath: string, content: Serializable) {
let contents = content
// if !isPrimitive?
if (typeof contents !== 'string') {
contents = stringify(content as any)
}
makePathIfNeeded(absolutePath)
return writeFileSync(absolutePath, contents, 'utf8')
}
read.json = readJSON
const exists = existsSync
export { read, write, readJSON, exists }