ice.fo.utils
Version:
32 lines (26 loc) • 766 B
JavaScript
import fs from 'fs';
import normalizePath from './normalizePath';
export default function writeFileSyncRecursive(filename, content, charset) {
let filepath = normalizePath(filename);
let root = '';
if (filepath[0] === '/') {
root = '/';
filepath = filepath.slice(1);
} else if (filepath[1] === ':') {
root = filepath.slice(0, 3); // c:\
filepath = filepath.slice(3);
}
const folders = filepath.split('/').slice(0, -1);
folders.reduce(
(acc, folder) => {
const folderPath = `${acc + folder}/`;
if (!fs.existsSync(folderPath)) {
fs.mkdirSync(folderPath);
}
return folderPath;
},
root, // first 'acc', important
);
// write file
fs.writeFileSync(root + filepath, content, charset);
}