How to use the writeJsonSync function from fs-extra

Find comprehensive JavaScript fs-extra.writeJsonSync code examples handpicked from public code repositorys.

fs-extra.writeJsonSync is a method provided by the fs-extra library that writes a JavaScript object to a JSON file on the file system, synchronously.

551
552
553
554
555
556
557
558
559
560
// Assuming all OK, copy over the master .config folder without overwriting (vendor package list, middleware)
if (uibRootFolderOK === true) {
    // Check if uibRoot/package.json exists and if not, create it
    const uibRootPkgJson = path.join(uib.rootFolder, 'package.json')
    if ( !fs.existsSync( uibRootPkgJson ) ) {
        fs.writeJsonSync( uibRootPkgJson, { name: 'uib-root' } )
    }
    // We want to always overwrite the .config template files
    const fsOpts = { 'overwrite': true, 'preserveTimestamps': true }
    try {
fork icon75
star icon352
watch icon25

+ 12 other calls in file

379
380
381
382
383
384
385
386
387
388

// Make sure it exists & contains valid JSON
if ( !fs.existsSync(fileName) ) {
    this.log.warn('[uibuilder:package-mgt:getUibRootPackageJson] No uibRoot/package.json file, creating minimal file.')
    // Create a minimal one
    fs.writeJsonSync(fileName, {
        'name': 'uib_root',
        'version': this.uib.version,
        'description': 'Root configuration and data folder for uibuilder',
        'scripts': {},
fork icon75
star icon346
watch icon24

+ 25 other calls in file

How does fs-extra.writeJsonSync work?

fs-extra.writeJsonSync is a method provided by the fs-extra library that writes a JavaScript object to a JSON file on the file system, synchronously. When you call fs-extra.writeJsonSync, you provide it with two arguments: the first argument is the path of the file to write to, and the second argument is the JavaScript object to write to the file. The fs-extra.writeJsonSync method will first stringify the JavaScript object into a JSON string using JSON.stringify(). It will then write this string to the file specified in the first argument, overwriting the file if it already exists. If the file does not exist, it will be created. By default, the fs-extra.writeJsonSync method will write the JSON with indentation for human readability. However, you can customize the formatting by providing an options object as a third argument to the method. The options object can include properties such as spaces to specify the number of spaces to use for indentation, or EOL to specify the end-of-line character to use. Overall, fs-extra.writeJsonSync is a convenient method for writing JavaScript objects to JSON files on the file system in a synchronous manner, and allows you to customize the formatting of the JSON file. However, as it is synchronous, it may block the main thread of execution, which can be a problem in certain situations.

15
16
17
18
19
20
21
22
23
24
if (!manifest) return { errors: ['Error writing manifest. Manifest is undefined.'] }
const uriPathname = manifest.id.replace(this.baseURI, '')
const outputPath = path.join(this.outputRoot, uriPathname)
try {
  fs.ensureDirSync(path.parse(outputPath).dir)
  fs.writeJsonSync(outputPath, manifest)
  return { messages: [`Generated manifest ${outputPath}`] }
} catch(error) {
  return { errors: [`Failed to write manifest. ${error}`] }
}
fork icon6
star icon63
watch icon15

+ 2 other calls in file

40
41
42
43
44
45
46
47
48
49
    packageContents.main = "app.js";
  }else{
    console.error('Could not add "main" to your src/package.json as it already exists');
  }

  fs.writeJsonSync('./src/package.json', packageContents);
} catch(e) {
  console.error('Could not add a "main" node to your src/package.json, you may need to add "main": "app.js" to your src/package.json');
  console.error(e);
}
fork icon3
star icon26
watch icon4

Ai Example

1
2
3
4
5
6
7
8
9
const fs = require("fs-extra");

const data = {
  name: "John Doe",
  email: "johndoe@example.com",
  phone: "+1-555-555-5555",
};

fs.writeJsonSync("data.json", data, { spaces: 2 });

In this example, we first import the fs-extra library. We then define a JavaScript object called data with some example data. We then call fs.writeJsonSync with three arguments: The first argument is the file path where the data should be written, which in this case is data.json. The second argument is the data object we want to write to the file, which is data. The third argument is an options object that specifies the number of spaces to use for indentation, which is set to 2 in this example. The fs-extra.writeJsonSync method will then write the data object to a JSON file at data.json, with indentation for human readability. If there is an error while writing the JSON to the file, an error will be thrown, so you should make sure to handle errors appropriately.

439
440
441
442
443
444
445
446
447
448
          overwrite: false,
          html: false,
          json: true,
      },
  };
  fs.writeJsonSync(reportConfigPath, reportConfig, { spaces: 4 });

  const runCommand = `npx cypress run \
--browser electron \
--config screenshotsFolder=${outputFolder} \
fork icon1
star icon3
watch icon2

+ 12 other calls in file

18
19
20
21
22
23
24
25
26
27
28
const fsExtra = require('fs-extra');
const glbToGltf = gltfPipeline.glbToGltf;
const glb = fsExtra.readFileSync('model.glb');
glbToGltf(glb)
    .then(function(results) {
        fsExtra.writeJsonSync('model.gltf', results.gltf);
    });
*/


//Converting a glTF to Draco glTF
fork icon0
star icon0
watch icon2

+ 39 other calls in file

266
267
268
269
270
271
272
273
274
275
276
    solutionsDir = resolve(root, "allSolutions/2_mediumSolutions");
  }else{
    solutionsDir = resolve(root, "allSolutions/3_hardSolutions");
  }


  fs.writeJsonSync(
    resolve(solutionsDir, `solution_${puzzleNumber}.json`),
    solution
  );
}
fork icon0
star icon0
watch icon1

+ 9 other calls in file

15
16
17
18
19
20
21
22
23
24
if (!manifest) return { errors: ['Error writing manifest. Manifest is undefined.'] }
const uri = new URL(manifest.id)
const outputPath = path.join(this.outputRoot, uri.pathname)
try {
  fs.ensureDirSync(path.parse(outputPath).dir)
  fs.writeJsonSync(outputPath, manifest, { spaces: 2 })
  return { messages: [`Generated manifest ${outputPath}`] }
} catch(error) {
  return { errors: [`Failed to write manifest. ${error}`] }
}
fork icon0
star icon0
watch icon1

187
188
189
190
191
192
193
194
195
196
  Fse.writeJsonSync(JSON_ELITE, elite);
  require('./updateTimestamp');
  console.log('Elite data updated.');
} else console.log('No need to update elite data.');
if (!Fse.existsSync(JSON_BASE_SKILL) || !_.isEqual(Fse.readJsonSync(JSON_BASE_SKILL), baseSkill)) {
  Fse.writeJsonSync(JSON_BASE_SKILL, baseSkill);
  require('./updateBase');
  require('./updateTimestamp');
  console.log('Base skill data updated.');
} else console.log('No need to update base skill data.');
fork icon0
star icon0
watch icon1

+ 14 other calls in file

71
72
73
74
75
76
77
78
79
80

packageJson.dependencies = packageJson.dependencies || {};
// add HTMLBars for templates (generators do this automatically when components/templates are added)
packageJson.dependencies['ember-cli-htmlbars'] = 'latest';

fs.writeJsonSync(packageJsonPath, packageJson);

let result = await runCommand('node_modules/ember-cli/bin/ember', 'build');

expect(result.code).to.eql(0);
fork icon0
star icon0
watch icon159

+ 3 other calls in file

function icon

fs-extra.readFileSync is the most popular function in fs-extra (9724 examples)