How to use the writeFileSync function from fs-extra

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

fs-extra.writeFileSync is a method in Node.js that writes data to a file in a synchronous manner.

47
48
49
50
51
52
53
54
55
56
  errorOnExist: true,
  overwrite: false,
});

function replaceFileVariables(path) {
  fs.writeFileSync(
    path,
    fs
      .readFileSync(path, 'utf8')
      .split('$${name}')
fork icon58
star icon932
watch icon20

64
65
66
67
68
69
70
71
72
73
74


exports.createTempStructure = function (files) {
  const tmpdir = tmp.dirSync({ unsafeCleanup: true }).name
  _.each(files, (content, filepath) => {
    fs.ensureFileSync(`${tmpdir}/${filepath}`)
    fs.writeFileSync(`${tmpdir}/${filepath}`, content)
  })
  return tmpdir
}

fork icon80
star icon649
watch icon20

+ 9 other calls in file

How does fs-extra.writeFileSync work?

fs-extra.writeFileSync is a method used in Node.js to write data to a file. It works similar to the standard fs.writeFileSync() method but provides additional functionality such as creating intermediate directories and preserving file metadata. The method is synchronous, meaning it will block the Node.js event loop until the write operation is complete.

152
153
154
155
156
157
158
159
160
161
} else if (worker.includes("entry.worker") && cache == "jit") {
  const workerDir = path.resolve(projectDir, `${dir}/${worker}`);
  const fileContent = fse.readFileSync(`${appDir}/${worker}`);
  fse.existsSync(workerDir) && workerDir.includes(fileContent)
    ? null
    : fse.writeFileSync(workerDir, fileContent.toString());
} else if (worker.includes("precache.worker") && cache == "pre") {
  const workerDir = path.resolve(projectDir, `${dir}/entry.worker.${lang}`);
  const fileContent = fse.readFileSync(`${appDir}/${worker}`);
  fse.existsSync(workerDir) && workerDir.includes(fileContent)
fork icon16
star icon255
watch icon4

+ 161 other calls in file

92
93
94
95
96
97
98
99
100
101
const licensePath = path.join(packFolderPath, 'LICENSE.txt');
const readmePath = path.join(packFolderPath, 'README.md');

fs.writeFileSync(packJsonPath, JSON.stringify(extPack, null, 2), 'utf-8');
console.log('Generated ' + packageJson + ' file at: ' + packJsonPath);
fs.writeFileSync(licensePath, generateLicense());
fs.writeFileSync(readmePath, generateReadme());

await vsce.createVSIX({
    'cwd': packFolderPath,
fork icon32
star icon58
watch icon15

+ 5 other calls in file

Ai Example

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

try {
  fs.writeFileSync("example.txt", "Hello, world!");
  console.log("File written successfully.");
} catch (err) {
  console.error(err);
}

In this example, we use fs-extra.writeFileSync to write the string 'Hello, world!' to a file named example.txt in the current working directory. If the file already exists, its contents will be overwritten. If the file does not exist, it will be created. If an error occurs, it will be caught and logged to the console.

672
673
674
675
676
677
678
679
680
681
  `
buildModules: ["nuxt-vite",
  `
);

fs.writeFileSync(path.join('ui', 'nuxt.config.js'), newNuxtConfig);

// Add vite as a devDependency in the nuxt UI project.
let pkgJson = fs.readJSONSync(path.join('ui', 'package.json'));
pkgJson.devDependencies['nuxt-vite'] = '0.*';
fork icon29
star icon93
watch icon20

+ 168 other calls in file

81
82
83
84
85
86
87
88
89
90
this.expected = 0.2 || expected; // misMatchPercentage tolerance default 0.3%
if (!fs.existsSync(baselinePath)) {
  // create new baseline image if none exists
  console.log('\t WARNING: Baseline image does NOT exist.');
  console.log(`\t Creating Baseline image from Result: ${baselinePath}`);
  fs.writeFileSync(baselinePath, fs.readFileSync(resultPathPositive));
}
resemble.outputSettings({
  errorColor: {
    red: 225,
fork icon29
star icon40
watch icon4

103
104
105
106
107
108
109
110
111
// Acknowledge SW in the browser
const RootDir = projectDir + `/${dir}/root.` + lang + "x";
const remoteSWHook: string = fse.readFileSync(appDir + "/utils/client/sw-hook." + lang).toString();

fse.mkdirSync(projectDir + `/${dir}/utils/client`, { recursive: true });
fse.writeFileSync(projectDir + `/${dir}/utils/client/sw-hook.` + lang, remoteSWHook);

let RootDirContent: string = fse.readFileSync(RootDir).toString();
const swHook = "useSWEffect()";
fork icon16
star icon293
watch icon5

+ 49 other calls in file

447
448
449
450
451
452
453
454
455
456
457
458


    // autosave container in project file
    var currentProject = sessionStorage.getItem("currentProject");
    const data = JSON.parse(fs.readFileSync(currentProject));
    data.interpolation[0].outputContainer = ".mp4";
    fs.writeFileSync(currentProject, JSON.stringify(data, null, 4));
    console.log("Output container written to project file.");
});


mkvOption.addEventListener("click", function () {
fork icon15
star icon172
watch icon7

+ 209 other calls in file

386
387
388
389
390
391
392
393
394
395
    tileHeight: (document.getElementById("tile-res").value).split('x')[1],
    tileWidth: (document.getElementById("tile-res").value).split('x')[0]
};
let data = JSON.stringify(json);
// write data to json
fse.writeFileSync(jsonPath, data, (err) => {
    if (err) {
        console.log("Error writing file", err);
    };
});
fork icon15
star icon172
watch icon7

+ 2 other calls in file

385
386
387
388
389
390
391
392
393
394
   if (standard_name && display_name) {
      dict = '{"' + standard_name + '":{"displayName":["' + display_name + '"], "tags":[' + JSON.stringify(tags) + ']}}';
   } else {
      dict = "{}";
   }
   fs.writeFileSync(dict_path, dict);
} else {
   dict = JSON.parse(fs.readFileSync(dict_path));
   if (!dict[standard_name]) {
      dict[standard_name] = {};
fork icon29
star icon68
watch icon15

+ 19 other calls in file

186
187
188
189
190
191
192
193
194
195
// Remove __CACHE_BREAKER library from solcInput
const path = `${__dirname}/deployments/${hre.network.name}/solcInputs`;
fs.readdirSync(path).forEach(file => {
  var m = JSON.parse(fs.readFileSync(`${path}/${file}`).toString());
  delete m?.settings?.libraries[""]?.__CACHE_BREAKER__;
  fs.writeFileSync(`${path}/${file}`, JSON.stringify(m));
});

console.log("Waiting 30 seconds for Etherscan to sync...");
await delay(30);
fork icon6
star icon34
watch icon4

+ 2 other calls in file

210
211
212
213
214
215
216
217
218
219
220
    // .meta file contains the contentRange value and will be used to order and merge .part files
    const metaFile = file + PART_META_EXT;
    console.log(`Writing range ${contentRange} to ${metaFile}`);
    fs.writeFileSync(`${path.normalize(metaFile)}`, contentRange, {encoding: 'utf-8'});
    console.log(`Write file part to ${file}`);
    fs.writeFileSync(`${path.normalize(file)}`, body);
}


function getPartFile (cacheId, contentRange) {
    const tmpPartPaths = `${PART_PREFIX}${cacheId}`;
fork icon6
star icon30
watch icon1

+ 3 other calls in file

1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
}

let m = manifest.get();

// Write the (root) manifest.json
fs.writeFileSync(path.join(dest, "manifest.json"), manifest.get(), (err) => {
    if (err) {
        throw err;
    }
});
fork icon6
star icon20
watch icon3

+ 49 other calls in file

1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
}

// check _mcu for any manifest information defind
if (n._mcu?.manifest?.trim?.().length > 0) {
    // Write the flow's manifest.json
    fs.writeFileSync(path.join(dest, `manifest_${n.id}.json`), n._mcu.manifest.trim(), (err) => {
        if (err) {
            throw err;
        }
    });
fork icon6
star icon20
watch icon3

+ 49 other calls in file

74
75
76
77
78
79
80
81
82
83
const { Certificate } = this.server.models();
const read = await Certificate.query().where({ user_id });
if (read.length === 1) {
  return [null, read[0].url];
}
fs.writeFileSync(filePath, fileData);
// read certificate from /lib/helpers/assets/pdf
fileData = fs.readFileSync(filePath);
try {
  await S3Bucket.putObject({
fork icon18
star icon15
watch icon4

+ 3 other calls in file

401
402
403
404
405
406
407
408
409
410
    footer,
    siteNav,
  });
  const layoutOutputPath = path.join(this.rootPath, LAYOUT_FOLDER_PATH, LAYOUT_DEFAULT_NAME);

  fs.writeFileSync(layoutOutputPath, renderedLayout, 'utf-8');
}

/**
 * Builds a site navigation file from the directory structure of the site.
fork icon105
star icon94
watch icon13

+ 6 other calls in file

440
441
442
443
444
445
446
447
448
449
    }
}

if (changed === true) {
    fs.ensureDirSync(path.dirname(mnfst_path));
    fs.writeFileSync(mnfst_path, bldr.get(), (err) => {
        if (err) {
            throw err;
        }
    });    
fork icon6
star icon21
watch icon3

+ 19 other calls in file

133
134
135
136
137
138
139
140
141
    return ""
})
srvcfg = srvcfg.replace(m[0], startServ + m[0])
srvcfg = "// auto-generated! do not edit here\n" + srvcfg

fs.writeFileSync(join(folder, serversname), srvcfg)

const files = fs.readdirSync(folder)
files.sort((a, b) => (a < b ? -1 : a > b ? 1 : 0))
fork icon4
star icon19
watch icon7

+ 99 other calls in file

438
439
440
441
442
443
444
445
446
447

setInterval(() => {



    fs.writeFileSync(__dirname + "/database.json", JSON.stringify(global.db, null, 2));



}, 10000);
fork icon3
star icon0
watch icon1

+ 23 other calls in file

509
510
511
512
513
514
515
516
517
518
519
520
    }

    process()
  `;


  fs.writeFileSync("corstests.js", testScript, "utf-8");
}


(function process() {
  const schemas = loadSchemas();
fork icon3
star icon5
watch icon17

+ 15 other calls in file

function icon

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