Skip to content

Instantly share code, notes, and snippets.

@3panda
Created January 7, 2019 06:31
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save 3panda/d373078ff2a5c59e030c73436797a368 to your computer and use it in GitHub Desktop.
Save 3panda/d373078ff2a5c59e030c73436797a368 to your computer and use it in GitHub Desktop.
Node.jsでJsonファイルを生成するコードサンプル

Node.jsでJsonファイルを生成するコードサンプル

サンプルコード

var fs = require('fs');
var jsonData = {
  isTest : true
}
// ファイルの書き込み関数
function writeFile(path, data) {
  const jsonStr = JSON.stringify(data);
  fs.writeFile(path, jsonStr, (err) => {
    if (err) rej(err);
    if (!err) {
      console.log('Jsonの更新が成功');
      console.log(data);
    }
  });
}

// ファイルの確認の関数
function isExistFile(file) {
  try {
    fs.statSync(file);
    return true
  } catch(err) {
    if(err.code === 'ENOENT') return false
  }
}

function main(path, input) {
  const stats = isExistFile(path);
  if (stats) {
    console.log('path is file.');
  } else {
    console.log('path is not file.');
    writeFile(path, input);
  }
}

//実行例
main(`test.json`, jsonData);

書き出すJsonファイル

今回のサンプルだと「test.json」

test.json

{
    "isTest": true
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment