All files / src smart-write.js

51.61% Statements 16/31
44.44% Branches 8/18
66.67% Functions 2/3
51.61% Lines 16/31
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100            8x   8x 8x                                   9x     9x 6x     3x     3x 2x     1x         7x 7x       3x 2x 1x     1x                                                                                      
import DefaultOptions from './default-options.js'
import ambifs from './fs-ambi'
import Path from 'path'
 
 
export default function smartwrite(path, value, options) {
	options = { ...DefaultOptions, ...options }
 
	Eif(options.async) {
		return write_async(path, value, options)
 
	} else {
		return write_sync(path, value, options)
 
	}
 
}
 
 
 
async function write_async(path, value, options) {
	let {
		json,
		replacer,
		reviver,
		space,
		...writeFileOpts
	} = options
 
	let finalValue
	if(json) {
		finalValue = JSON.stringify(value)
 
	} else {
		Iif (value === undefined) {
			finalValue = ''
 
		} else if(typeof value !== 'string') {
			throw new TypeError(`${typeof value} is not a string`)
 
		} else {
			finalValue = value
 
		}
	}
 
	try {
		return await ambifs.writeFile(path, finalValue, writeFileOpts)
 
	} catch(error) {
		// we swallow "dirs don't exist" errors because we can remedy that
		if(error.code === 'ENOENT') {
			await ambifs.mkdirp(Path.dirname(path), writeFileOpts)
			return write_async(path, value, options)
		}
 
		throw error
 
	}
}
 
 
 
function write_sync(path, value, options) {
	let {
		json,
		replacer,
		reviver,
		space,
		...writeFileOpts
	} = options
 
	let finalValue
	if (json) {
		finalValue = JSON.stringify(value)
 
	} else {
		if (value === undefined) {
			finalValue = ''
 
		} else if (typeof value !== 'string') {
			throw new Error(`${typeof value} is not a string`)
 
		}
	}
 
	try {
		return ambifs.writeFile(path, finalValue, writeFileOpts)
 
	} catch (error) {
		if(error.code === 'ENOENT') {
			ambifs.mkdirp(Path.dirname(path), writeFileOpts)
			return write_sync(path, value, options)
		}
 
		throw error
 
	}
}