Skip to content

Instantly share code, notes, and snippets.

@wjramos
Created May 25, 2018 00:16
Show Gist options
  • Save wjramos/eb3c1c3dbbbdd9c86d3c4ba8875e1366 to your computer and use it in GitHub Desktop.
Save wjramos/eb3c1c3dbbbdd9c86d3c4ba8875e1366 to your computer and use it in GitHub Desktop.
file system utils
// *******************
// Filesystem utils
// *****************
export const isDirectory = source => fs.lstatSync(source).isDirectory();
export const removePath = (source, filePaths = []) => filePaths.map(filePath => filePath.replace(source, ''));
export const listDirFiles = source => fs.readdirSync(source).map(name => path.join(source, name));
export const listFiles = source => listDirFiles(source).filter(source => !isDirectory(source));
export const listDirs = source => listDirFiles(source).filter(isDirectory);
export const removeExtension = fileName => fileName.split('.')[0];
export const getFileName = filePath => removeExtension(filePath.split('/').pop());
// Recursively creates nested directory structure from specified path
export function mkdirp(path) {
path.split('/').slice(0, -1).reduce((prev, cur) => {
const newPath = `${prev}/${cur}`;
if (!fs.existsSync(newPath)) {
fs.mkdirSync(newPath);
}
return newPath;
});
}
export function writeFile(path, data) {
try {
console.log(`Writing file: ${path}`);
mkdirp(path);
fs.writeFileSync(path, JSON.stringify(data));
} catch (err) {
console.error(err);
process.exit(1);
}
}
export function readFile(path) {
try {
return fs.readFileSync(path, 'utf8');
} catch (err) {
console.error(err);
process.exit(1);
}
}
export function rmrf(dirPath) {
if (fs.existsSync(dirPath)) {
fs.readdirSync(dirPath).forEach((fileName) => {
const filePath = path.join(dirPath, fileName);
console.log(`Deleting ${filePath}`);
if (isDirectory(filePath)) {
rmrf(filePath);
} else {
fs.unlinkSync(filePath);
}
});
console.log(`Deleting ${dirPath}`);
fs.rmdirSync(dirPath);
}
}
export const emptyDir = dirPath => rmrf(`${dirPath}/*`);
export const copyFiles = (inputPath, outputPath) => fs.readdirSync(inputPath)
.forEach((fileName) => {
const destination = `${outputPath}/${fileName}`;
mkdirp(destination);
const inStream = fs.createReadStream(`${inputPath}/${fileName}`);
const outStream = fs.createWriteStream(destination);
console.log(`Copying file ${fileName} from ${inputPath} to ${destination}`);
inStream.pipe(outStream);
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment