All files / src smart-read.js

67.86% Statements 19/28
64.29% Branches 9/14
75% Functions 3/4
66.67% Lines 16/24
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          5x   5x 5x                                   5x     5x 5x       1x             4x                                                             4x   3x 3x       2x 2x 2x   2x     1x        
import DefaultOptions from './default-options.js'
import ambifs from './fs-ambi'
 
 
export default function smartread(path, options) {
	options = { ...DefaultOptions, ...options }
 
	Eif(options.async) {
		return read_async(path, options)
 
	} else {
		return read_sync(path, options)
 
	}
 
}
 
 
 
async function read_async(path, options) {
	let {
		json,
		replacer,
		reviver,
		space,
		...readFileOpts
	} = options
 
	let contents
	try {
		contents = await ambifs.readFile(path, readFileOpts)
 
	} catch (error) {
		// special handling: return undefined for non-existent files
		Eif (error.code === 'ENOENT') return
 
		throw error
 
	}
 
 
	return grokFile(contents, json, reviver)
}
 
 
 
function read_sync(path, options) {
	let {
		json,
		replacer,
		reviver,
		space,
		...readFileOpts
	} = options
 
	let contents
	try {
		contents = ambifs.readFile(path, readFileOpts)
 
	} catch (error) {
		// special handling: return undefined for non-existent files
		if (error.code === 'ENOENT') return
 
		throw error
	}
 
	return grokFile(contents, json, reviver)
}
 
 
 
function grokFile(contents, json, reviver) {
	if (!json) return contents
 
	try {
		return JSON.parse(contents, reviver)
 
	} catch (error) {
		// special handling: returned undefined if file is (essentially) blank, or is text "undefined"
		Eif(error instanceof SyntaxError) {
			let trimmed = String(contents).trim()
			let fileIsEmpty = trimmed === '' || trimmed === 'undefined'
 
			if(fileIsEmpty) return
		}
 
		throw error
 
	}
}