@almaclaine/fs-utils
Version:
Utilities for working with the file system.
67 lines • 2.15 kB
JavaScript
import { lstatSync, existsSync, readdirSync, readFileSync as fsReadFileSync, writeFileSync, mkdirSync, createReadStream as fsCreateReadStream } from 'fs';
import { join, sep } from 'path';
import { alreadyExistsError, doesNotExistError, isDirectoryError, isNotDirectoryError, isNotJsonFilError } from "./errorTemplates";
export { join, resolve } from 'path';
export { existsSync, copyFileSync } from 'fs';
export function isHidden(path) {
const pathSplit = path.split(sep);
return pathSplit[pathSplit.length - 1][0] === '.';
}
export function createReadStream(path) {
if (!existsSync(path)) {
throw Error(doesNotExistError(path));
}
return fsCreateReadStream(path);
}
export const makeCwdRelPath = (...files) => join(process.cwd(), ...files);
export function isDirectorySync(path) {
if (!existsSync(path))
return false;
return lstatSync(path).isDirectory();
}
export function readDirectorySync(path) {
if (!isDirectorySync(path)) {
throw Error(isNotDirectoryError(path));
}
return readdirSync(path);
}
export function makeDirectorySync(path) {
if (existsSync(path)) {
throw Error(alreadyExistsError(path));
}
mkdirSync(path);
}
export function importJson(path) {
if (!existsSync(path)) {
throw Error(doesNotExistError(path));
}
if (!/.*\.json/.test(path)) {
throw Error(isNotJsonFilError(path));
}
return require(path);
}
export function readFileAsStringSync(path) {
if (!existsSync(path)) {
throw Error(doesNotExistError(path));
}
if (isDirectorySync(path)) {
throw Error(isNotDirectoryError(path));
}
return fsReadFileSync(path, 'utf-8');
}
export function readFileSync(path) {
if (!existsSync(path)) {
throw Error(doesNotExistError(path));
}
if (isDirectorySync(path)) {
throw Error(isNotDirectoryError(path));
}
return fsReadFileSync(path);
}
export function writeFileAsStringSync(path, data) {
if (isDirectorySync(path)) {
throw Error(isDirectoryError(path));
}
writeFileSync(path, data, 'utf-8');
}
//# sourceMappingURL=fs-utils.js.map