How to use the writeFile function from fs-extra

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

fs-extra.writeFile is a function provided by the fs-extra library that writes data to a file on the file system, creating the file if it doesn't exist or overwriting it if it does.

399
400
401
402
403
404
405
406
407
408
try {
  await fse.ensureDir(path.dirname(sourceFile));
  if (localPath) {
    await fse.copy(localPath, sourceFile);
  } else {
    await fse.writeFile(sourceFile, buffer);
  }
} catch (err) {
  debug(`File ${name} could not be written`, err);
}
fork icon253
star icon252
watch icon0

318
319
320
321
322
323
324
325
326
327
328
329
    const newVersion =
        versionParts.length > 1 ? `${versionParts[0]}.${versionParts[1]}.${buildNumber}` : packageJson.version;
    packageJson.version = newVersion;


    // Write back to the package json
    await fs.writeFile('package.json', JSON.stringify(packageJson, null, 4), 'utf-8');
}


async function buildWebPack(webpackConfigName, args, env) {
    // Remember to perform a case insensitive search.
fork icon209
star icon955
watch icon43

+ 9 other calls in file

How does fs-extra.writeFile work?

fs-extra.writeFile works by writing data to a file on the file system, creating the file if it doesn't exist or overwriting it if it does.

When called, fs-extra.writeFile takes two or three arguments. The first argument is the path to the file to be written, and the second argument is the data to be written to the file. The third argument, which is optional, is an options object that can be used to configure the behavior of the function.

The fs-extra.writeFile function then performs a series of operations to write the data to the file, including opening the file for writing, writing the data to the file, and closing the file when finished. If the file already exists, it will be overwritten by the new data.

Once the data has been written to the file, fs-extra.writeFile returns a Promise that resolves to undefined.

By using fs-extra.writeFile, Node.js developers can programmatically write data to files on the file system, allowing them to persist data between different runs of their application, generate static files for a web server, or perform other file-related operations.

300
301
302
303
304
305
306
307
308
309

const copyFile = (fileName) => fs.copy(path.join(kitRoot, fileName), path.join(installDirectory, fileName))

await Promise.all([
  createStarterFiles(installDirectory),
  fs.writeFile(path.join(installDirectory, '.gitignore'), gitignore, 'utf8'),
  fs.writeFile(path.join(installDirectory, '.npmrc'), npmrc, 'utf8'),
  copyFile('LICENCE.txt'),
  updatePackageJson(path.join(installDirectory, 'package.json'))
])
fork icon234
star icon281
watch icon77

+ 11 other calls in file

122
123
124
125
126
127
128
129
130
131
  // icns.addFromPng(iconFile, ['ic14'], raw);
  // icns.addFromPng(iconFile, ['ic10'], raw);
  // icns.addFromPng(iconFile, ['ic11'], raw);
}
// save icns file
await fs.writeFile(
  path.resolve(
    process.cwd(),
    `${appDistributionName}.app`,
    "Contents",
fork icon15
star icon187
watch icon0

+ 2 other calls in file

Ai Example

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

// write some data to a file using fs-extra.writeFile
fs.writeFile("./path/to/file.txt", "Hello, world!")
  .then(() => {
    console.log("Data written to file successfully!");
  })
  .catch((err) => {
    console.error(`Error writing to file: ${err}`);
  });

In this example, we're using fs-extra.writeFile to write some data ('Hello, world!') to a file located at ./path/to/file.txt. We call the function and pass the file path and data as arguments, and then attach a .then() method to the returned Promise to log a success message to the console. If an error occurs during the write operation, we attach a .catch() method to the Promise to log an error message instead. When we run this code, it will either log a success message or an error message to the console, depending on whether the write operation was successful or not. If the write operation was successful, the message logged to the console will be: css Copy code

114
115
116
117
118
119
120
121
122
123
124
125


fs.ensureDirSync (destination);


function writeFile (file, content) {
  file = path.join(destination, file);
  fs.writeFile(file, content, function (err) {
    if (err) {
      console.error('Failed to write ' + file + ': ' + err);
    }
  });
fork icon84
star icon65
watch icon0

554
555
556
557
558
559
560
561
562
563
if ( params.folder === 'root' ) params.folder = '.'

const fullname = path.join(uib.rootFolder, params.url, params.folder, params.fname)

// eslint-disable-next-line no-unused-vars
fs.writeFile(fullname, req.body.data, function (err, data) {
    if (err) {
        // Send back a response message and code 200 = OK, 500 (Internal Server Error)=Update failed
        log.error(`[uibuilder:apiv2:uibputfile] Admin API. File write FAIL. url=${params.url}, file=${params.folder}/${params.fname}`, err)
        res.statusMessage = err
fork icon75
star icon346
watch icon24

+ 12 other calls in file

140
141
142
143
144
145
146
147
148
149
	await fs.mkdirs(directory);
}
let temporary = `${file}.tmp`;
let fd = await fs.open(temporary, "w");
try {
	await fs.writeFile(fd, data, options);
	await fs.fsync(fd);
} finally {
	await fs.close(fd);
}
fork icon58
star icon228
watch icon0

176
177
178
179
180
181
182
183
184
    }

    const currPath = utils.getCurrentPath(this);
    const localPath = path.resolve(tmp.tmpdir, currPath);
    await utils.makeDirFor(localPath);
    await fs.writeFile(localPath, new Buffer(this.screenshot.base64, 'base64'), 'base64');

    return this._saveImg(localPath, currPath, reportPath);
}
fork icon38
star icon39
watch icon5

+ 5 other calls in file

296
297
298
299
300
301
302
303
304
305
      });
   }

   membersFile = JSON.stringify(membersFile);

   fs.writeFile(path.join(groupFolder, 'members.json'), membersFile, function() {
      next();
   });
} else {
   res.status(401).send();
fork icon29
star icon68
watch icon15

+ 3 other calls in file

174
175
176
177
178
179
180
181
182
183
	const fs = require('fs-extra');
	let content = await fs.readFile(filePath, 'utf-8');
	// [^]* matches any character including new lines
	const regex = new RegExp(`${markerOpen}[^]*?${markerClose}`);
	content = content.replace(regex, markerOpen + contentToInsert + markerClose);
	await fs.writeFile(filePath, content);
};


module.exports = toolUtils;
fork icon8
star icon43
watch icon13

+ 8 other calls in file

148
149
150
151
152
153
154
155
156
157
158
  "include": ["next-env.d.ts", "**/*.ts", "**/*.tsx"],
  "exclude": ["node_modules"]
}
  `;


  await fs.writeFile(sysPath.join(root, `./src/index.d.ts`), shader);
  await fs.writeFile(sysPath.join(root, "tsconfig.json"), tsconfig, {
    spaces: 2,
  });
  await fs.remove(sysPath.join(root, "jsconfig.json"));
fork icon5
star icon36
watch icon0

+ 11 other calls in file

236
237
238
239
240
241
242
243
244
245
    }
    // frontmatter.head.modules = [
    //   ...(frontmatter.modules ?? []),
    //   '/assets/js/code-playground.min.js',
    // ];
    fs.writeFile(dest + '.md', matter.stringify(content, frontmatter));
  } catch (e) {
    console.error('Error parsing', x, e);
  }
}
fork icon11
star icon33
watch icon0

+ 9 other calls in file

20
21
22
23
24
25
26
27
28
29
    const result = sass.renderSync({
      file: path.join(srcDir, file),
    });
    // Create cssPath directory recursively
    // Then write result css string to cssPath file
    fs.writeFile(path.format(p), result.css.toString()).catch((error) =>
      console.error(error)
    );
  }
});
fork icon9
star icon32
watch icon2

+ 8 other calls in file

420
421
422
423
424
425
426
427
428
429
const start = async ({ args, cwd, env, patterns }) => {
  if (patterns && patterns.length) {
    const pkgPath = path.resolve(cwd, 'package.json');
    const pkg = JSON.parse(await fs.readFile(pkgPath, 'utf8'));
    pkg.electronmon = { patterns };
    await fs.writeFile(pkgPath, JSON.stringify(pkg));
  }

  app = spawn(process.execPath, [cli].concat(args), {
    env,
fork icon7
star icon86
watch icon2

+ 51 other calls in file

216
217
218
219
220
221
222
223
224
225
    });
});

router.post("/saveCommandList", async (req, res) => {
    
    fs.writeFile(backendDir+"/settings/commands.json", JSON.stringify(req.body), "utf-8", (err, data)=>{
        events = req.body.events;
        eventGroups = req.body.groups;
        res.send({status:"SAVE SUCCESS"});
        webLog("SAVED COMMANDS");
fork icon3
star icon30
watch icon0

+ 11 other calls in file

161
162
163
164
165
166
167
168
169
170
try {
  fs.ensureDirSync(plugindir);
} catch (err) {
  console.log('Cannot Create Plugin Dir ' + plugindir);
}
fs.writeFile(plugindir + '/' + this.uniquename, this.fileData, (err) => {
  if (err) {
    console.log('Plugin upload failed: ' + err);
  } else {
    var socket = io.connect('http://localhost:3000');
fork icon28
star icon21
watch icon4

+ 20 other calls in file

234
235
236
237
238
239
240
241
242
243
244
    .then(async (res) => {
      res.warnings().forEach((warn) => {
        console.warn(warn.toString());
      });


      await fsExtra.writeFile(dest, res.css);
      console.timeEnd(labelForBuild);
    });
}

fork icon9
star icon18
watch icon0

+ 3 other calls in file

523
524
525
526
527
528
529
530
531
532
} else {
    mcu_plugin_config.cache_data = data;
}

let cache_data = JSON.stringify(data);
fs.writeFile(mcu_plugin_config.cache_file, cache_data, err => {
    if (err) {
        RED.log.warn(`${app_name}: Failed to persist config to cache @ ${mcu_plugin_config.cache_file}.`);
    }
})
fork icon6
star icon21
watch icon3

+ 9 other calls in file

36
37
38
39
40
41
42
43
44
45
  reject(err);
  return;
}

try {
  await fs.writeFile(path, templateString, 'utf-8');
  await this.bucketManager.DeployLambdaPromise(this.deploymentBucket, path, templateRelativeUrl);
  resolve();
} catch (asyncError) {
  reject(asyncError);
fork icon4
star icon31
watch icon3

+ 11 other calls in file

1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
    filename = `Cover/${await getCover(current, lulu.numpages, {hasExtraPadding: true})}.pdf`;
    await fs.copy(`./PDF/Letter/${filename}`, `./PDF/Letter/Finished/${zipFilename}/Publication/Cover_PerfectBound.pdf`);
}
else {
    let notice = `Your LibreText of ${lulu.numpages} is below the minimum of 32 for Perfect Bound. Please use one of the other bindings or increase the number of pages`;
    await fs.writeFile(`./PDF/Letter/Finished/${zipFilename}/Publication/Notice_PerfectBound.txt`, notice);
}
if (lulu.numpages >= 24) {
    filename = `Cover/${await getCover(current, lulu.numpages, {
        hasExtraPadding: true,
fork icon8
star icon11
watch icon6

+ 53 other calls in file

function icon

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