The use case is I use the ensureFile to create json file if it not created before, but I need to inject the {} into it first time because the jsonfile readFile method will throw the Unexpected end of JSON input error when the json file is empty.
I think it would be nice if support that, such as, I can do it by the code below
function renderBundleJSON(file, map) {
return fse.ensureFile(file).then(isExist => {
if (!isExist) {
fse.writeJSONSync(file, {});
}
return fse.readJson(file).then(json => {
return fse.outputJson(file, Object.assign(json, map), {
spaces: 2
});
});
});
}
But I workaround it by
function renderBundleJSON(file, map) {
return fse.ensureFile(file).then(() => {
return fse
.readJson(file)
.then(json => {
return fse.outputJson(file, Object.assign(json, map), {
spaces: 2
});
})
.catch(err => {
// here
return fse.writeJson(file, {}).then(() => renderBundleJSON(file, map));
});
});
}
@monkindey Using ensureFile here is an anti-pattern, because it means an extra filesystem operation if the file doesn't exist.
Here's a better way to do it; assuming that file will never be a directory or a file that isn't valid JSON:
function renderBundleJSON(file, map) {
return fse.pathExists(file)
.then(isExist => isExist ? fse.readJson(file) : Promise.resolve({}))
.then(json => {
return fse.outputJson(file, Object.assign(json, map), {
spaces: 2
});
});
}
Thanks for your reply, learn a lot from you. I think it will solve my problem, and I will try it tomorrow.
Appreciate your help !