Skip to content

Instantly share code, notes, and snippets.

@cathalnoonan
Created July 12, 2021 19:13
Show Gist options
  • Save cathalnoonan/35a2cc9df0392bbc0e227f113794812d to your computer and use it in GitHub Desktop.
Save cathalnoonan/35a2cc9df0392bbc0e227f113794812d to your computer and use it in GitHub Desktop.
Node.js : indentJsonFile -- Replaces the content of a JSON file with indentation added
const fs = require('fs').promises
/**
* Overwrites the content of a JSON file with indentation added.
* @param {string} filePath Path to the JSON file.
* @param {number} indentation Number of spaces used in indentation.
* @returns {Promise<void>}
*/
async function indentJsonFile (filePath, indentation = 2) {
const fileContent = await fs.readFile(filePath, { encoding: 'utf-8' })
const json = JSON.stringify(JSON.parse(fileContent), null, indentation)
await fs.writeFile(filePath, json)
}
// Sample call
await indentJsonFile('./path/to/file.json', 2)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment