lib/file.js

const fs = require('node:fs');
const path = require('node:path');

/**
 * @module pete/lib/file
 */
module.exports.file = file;

/**
 * File system module
 *
 * @external fs
 * @see {@link https://nodejs.org/api/fs.html}
 */

/**
 * File write stream
 *
 * @typedef external:fs.WriteStream
 * @see {@link https://nodejs.org/api/fs.html#fs_class_fs_writestream}
 */

/**
 * Creates directory tree if needed to make the file path available.
 * Creates the file if needed.
 *
 * @alias module:pete/lib/file
 * @throws {Error} when trying to open file outside of current directory
 * @param {string}  filepath
 * @param {boolean} [overwrite=false]
 * @return {external:fs.WriteStream}
 */
function file (filepath, overwrite = false) {
	const dir = process.env.PWD || process.cwd();
	const target = path.resolve(dir, filepath);

	if (target.indexOf(dir) !== 0) {
		throw new Error(`Writing to file outside of ${dir} is not allowed`);
	}

	fs.mkdirSync(path.dirname(target), {recursive: true});
	return fs.createWriteStream(target, {flags: overwrite ? 'w' : 'a+'});
}