var fs = require('fs');
var jsonData = {
isTest : true
}
function main(path, input) {
return new Promise((res, rej) => {
fs.readFile(path, 'utf8', (err, data) => {
if (err) {
if(err.code = `ENOENT`) {
const jsonStr = JSON.stringify(input);
fs.writeFile(path, jsonStr, (err) => {
if (err) rej(err);
if (!err) {
console.log('Jsonの作成');
}
});
} else {
console.log(`エラー`);
rej(err);
}
} else {
console.log(`読み込み成功`);
const response = JSON.parse(data);
console.log(response);
res(response);
}
});
});
}
//使用例
const json = main(`test.json`, jsonData);
console.log(json);
今回のサンプルだと「test.json」
test.json
{
"isTest": true
}