All files fileUtils.js

100% Statements 13/13
100% Branches 3/3
100% Functions 4/4
100% Lines 13/13

Press n or j to go to the next uncovered block, b, p or k for the previous block.

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    1x 1x 1x     1x                     3756x     3756x 3756x 1x       3755x       13x           404x       45x     1x            
'use strict';
 
const fs = require( 'fs' );
const path = require( 'path' );
const yaml = require( 'yaml' );
 
// Have a file size read upper limit of 10 MiB for safety.
const upperfileSizeLimit = 10 * 1024 * 1024;
 
/**
 * Internal method to load a given file, but limited for safety to 10 MiB
 *
 * @param {string} fileName
 * @param {number} fileSizeLimit
 * @return {string}
 */
function readFileLimited( fileName, fileSizeLimit = upperfileSizeLimit ) {
	// Have a file size read upper limit of 10 MiB for safety.
	fileSizeLimit = Math.min( fileSizeLimit, upperfileSizeLimit );
 
	// eslint-disable-next-line security/detect-non-literal-fs-filename
	const stats = fs.statSync( fileName );
	if ( stats.size > fileSizeLimit ) {
		throw new Error( 'File ' + fileName + ' is larger than the maximum permitted size, ' + fileSizeLimit + ' bytes' );
	}
 
	// eslint-disable-next-line security/detect-non-literal-fs-filename
	return fs.readFileSync( fileName, { encoding: 'utf8', start: 0, end: fileSizeLimit } );
}
 
function dataDir( ...pathComponents ) {
	return path.join(
		path.dirname( path.dirname( path.dirname( __filename ) ) ),
		'data', ...pathComponents );
}
 
function readYaml( fileName ) {
	return yaml.parse( readFileLimited( fileName ) );
}
 
function readJSON( fileName ) {
	return JSON.parse( readFileLimited( fileName ) );
}
 
module.exports = {
	dataDir,
	readFileLimited,
	readJSON,
	readYaml
};