Skip to content

Instantly share code, notes, and snippets.

@classLfz
Last active October 9, 2018 05:16
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save classLfz/53798fd58b5b2fa5e7a5a1eb60e2a386 to your computer and use it in GitHub Desktop.
Save classLfz/53798fd58b5b2fa5e7a5a1eb60e2a386 to your computer and use it in GitHub Desktop.
useful nodejs functions
/**
* create folder sync
* @param {String} rootPath root path.
* @param {String} folderPath folder base on root path.
* @returns {Boolean} created
*/
function mkdirsSync (rootPath, folderPath) {
let dirPath = path.join(rootPath, folderPath)
if (fs.existsSync(dirPath)) {
return true
} else {
if (mkdirsSync(rootPath, path.dirname(folderPath))) {
fs.mkdirSync(dirPath)
return true
}
}
}
/**
* delete folder recursive sync.
* @param {String} path path to delete.
*/
function deleteFolderRecursive (path) {
if (fs.existsSync(path)) {
fs.readdirSync(path).forEach(function (file) {
var curPath = path + '/' + file
if (fs.lstatSync(curPath).isDirectory()) {
deleteFolderRecursive(curPath)
} else {
fs.unlinkSync(curPath)
}
})
fs.rmdirSync(path)
}
}
/**
* read folder size
* @param {String} path folder path.
* @returns {Number} folder size number.
*/
function readFolderSize (path) {
if (fs.existsSync(path)) {
var size = 0
fs.readdirSync(path).forEach(file => {
var curPath = path + '/' + file
if (fs.lstatSync(curPath).isDirectory()) {
size += readSize(curPath)
} else {
size += fs.statSync(curPath).size
}
})
return size
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment