Last active
February 9, 2021 13:33
-
-
Save mmanishh/49ba2e3e2515bb1e4fc0fb06e6b53d2e to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const fs = require('fs'); | |
/* | |
checks if dir exists , if not create the dir with path passed | |
@params {String} path : path of dir to check if exists | |
@returns {Promise} promise : Promise of path of dir created or existed | |
*/ | |
async function createDirIfNotExists(path) { | |
if (!path) throw new Error("Path should not be null") | |
if (!fs.existsSync(path)) { | |
fs.mkdirSync(path, { recursive: true }); | |
} | |
return Promise.resolve(path) | |
} | |
/* | |
Write data into the file with path passed | |
@params {String} path : path of dir to to write | |
@params {Object} data : data to write | |
@returns {Promise} promise : resolved promise if write is successful , else reject promise | |
*/ | |
async function writeJSON(path, data) { | |
//checking if data is object | |
if (typeof data !== 'object' || data === null) { | |
return Promise.reject(new Error("Invalid data")) | |
} | |
let [splittedPath, fileName] = getDirPathAndFile(path); | |
splittedPath = await createDirIfNotExists(splittedPath); | |
data = JSON.stringify(data); | |
fs.writeFile(splittedPath + "/" + fileName, data, function (err) { | |
if (err) { | |
throw Promise.reject(err) | |
} | |
return Promise.resolve() | |
}); | |
} | |
/* | |
get dir path and file name for a give path | |
@params {String} path : path of dir to to write | |
@returns {Array} [dirPath, fileName] : [dirPath, fileName] | |
*/ | |
function getDirPathAndFile(path) { | |
return [path.split("/").slice(0, -1).join('/'), path.split("/").pop()] | |
} | |
module.exports = { createDirIfNotExists, writeJSON } | |
//console.log(getDirPathAndFile("/Users/user/codes/sarojtask/test")) | |
/* createDirIfNotExists("/Users/user / codes / sarojtask / test") | |
.then(res => console.log(res)) | |
.catch(err => console.log(err)) */ | |
/* writeJSON("/Users/user/codes/sarojtask/a/b/c", { data: "s" }) | |
.then(res => console.log(res)) | |
.catch(err => console.log(err)) */ |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment