Created
July 12, 2021 19:13
-
-
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
This file contains 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').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