How to use the outputFile function from fs-extra

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

fs-extra.outputFile is a method in Node.js that writes data to a file and creates the file if it doesn't exist.

291
292
293
294
295
296
297
298
299
300
  const filepath = path.join(tempAppDir, filename);
  fs.existsSync(filepath).should.be.true(`failed to create ${filename}`);
});

// needed for the test below which expects to be able to import core
await fs.outputFile(
  path.join(
    tempAppDir,
    'node_modules',
    'zapier-platform-core',
fork icon168
star icon237
watch icon0

2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
    delete jobInfo[key];
}

try {
    this.lastWriteTimeJobInfo = Date.now();
    await fs.outputFile(CURRENT_INFO_FILE, JSON.stringify(jobInfo, null, 4), 'utf8');
    await fs.copy(CURRENT_INFO_FILE, CURRENT_INFO_FILE + '.bak');
    
    for (var key of nonWriteable) {
        jobInfo[key] = savedData[key];
fork icon82
star icon94
watch icon26

+ 3 other calls in file

How does fs-extra.outputFile work?

fs-extra.outputFile is a function provided by the fs-extra module in Node.js that creates a new file with the specified content or updates an existing file with new content by overwriting the existing content. It first creates the parent directory of the file if it does not exist and then writes the content to the specified file. The function returns a Promise that resolves when the file has been successfully written or rejects with an error if the file could not be written.

121
122
123
124
125
126
127
128
129
130
131
132
133
  var gitconfigPath   = path.join(localPath, '.git/config');
  var maskedGitconfig = toolkit.safeReadFileSync(gitconfigPath);


  var gitconfig = maskedGitconfig.replace(`url = ${_getGitRepoAuthURL(scriptMarket, true)}`, `url = ${_getGitRepoAuthURL(scriptMarket)}`);


  fs.outputFile(gitconfigPath, gitconfig, callback);
};


function _getToken(scriptMarket) {
  if (!scriptMarket.id) {
fork icon34
star icon185
watch icon0

+ 2 other calls in file

367
368
369
370
371
372
373
374
375
376
    await fs.access(aboutPath);
  } catch (error) {
    if (fs.existsSync(aboutPath)) {
      return;
    }
    await fs.outputFile(aboutPath, ABOUT_MARKDOWN_DEFAULT);
  }
}

/**
fork icon106
star icon94
watch icon13

Ai Example

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

const data =
  "This is some sample data that will be written to a file using fs-extra.";
const filePath = "/path/to/file.txt";

fs.outputFile(filePath, data)
  .then(() => console.log("Data written to file successfully"))
  .catch((err) => console.error(err));

In this example, fs-extra.outputFile is used to write data to the file at filePath. If the file does not exist, it will be created. If it does exist, it will be overwritten with the new data. The promise returned by fs-extra.outputFile is used to handle success and error cases. If the data is written successfully, the message "Data written to file successfully" is logged to the console. If an error occurs, the error message is logged to the console.

38
39
40
41
42
43
44
45
46
47
48
49
    return undefined
  }


  const response = await request.get(url, { encoding: null })
  console.log('Writing:', targetFile)
  return fs.outputFile(targetFile, response)
}


const launchServer = async () => {
  const server = await createServer(config)
fork icon31
star icon938
watch icon25

+ 10 other calls in file

2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
    VlocityUtils.report('Diffs', totalDiffs);
    VlocityUtils.report('New', totalNew);
    VlocityUtils.report('Undiffable', totalUndiffable);


    await Promise.all([
        fs.outputFile(path.join(this.vlocity.tempFolder, 'diffs/localFolderFiles.json'), stringify_pretty(currentFiles, { space: 4 })),
        fs.outputFile(path.join(this.vlocity.tempFolder, 'diffs/targetOrgFiles.json'), stringify_pretty(exportedFiles, { space: 4 }))
    ]);
};

fork icon80
star icon94
watch icon26

+ 71 other calls in file

51
52
53
54
55
56
57
58
59
60
61
62
  })
  return store.getQuads()
})


const createData = ({ path, data }) =>
  fs.outputFile(`public${path}`, data, (err) => err && console.error(err))


const getTurtleFiles = function (dirPath, arrayOfFiles) {
  const files = fs.readdirSync(dirPath)
  arrayOfFiles = arrayOfFiles || []
fork icon21
star icon23
watch icon0

+ 2 other calls in file

1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
if (event.code === 'ERROR') {
	if (event.error.message !== 'Expected render error') {
		reject(event.error);
	}
	await wait(300);
	await outputFile(ID_MAIN, 'console.log(43);');
} else if (event.code === 'BUNDLE_END') {
	await event.result.close();
	resolve();
}
fork icon7
star icon17
watch icon1

+ 71 other calls in file

146
147
148
149
150
151
152
153
154
155
156
*/
}


FS.outputFileAtomic = function (path, data, callback) {
	var tmpPath = path + '~' + Date.now();
    return FS.outputFile(tmpPath, data, function (err) {
    	if (err) return callback(err);
    	// Assume file exists.
    	return FS.unlink(path, function () {
    		// We ignore error.
fork icon2
star icon10
watch icon0

+ 6 other calls in file

128
129
130
131
132
133
134
135
136
137
138
  }
});


Import.post("/cancel/:importID", async function (req, res) {
  try {
    await fs.outputFile(join(req.importDirectory, "cancelled.txt"), "true");
  } catch (e) {
    return res.message(req.baseUrl, new Error("Failed to cancel import"));
  }

fork icon69
star icon0
watch icon23

+ 19 other calls in file

32
33
34
35
36
37
38
39
40
41

const packageJSON = join(cwd, dir, 'package.json');
await fs.outputJson(packageJSON, generatePackageJSON(dir, dbengine), { spaces: 2 });

const sql = join(cwd, dir, 'db', 'tasks.sql');
await fs.outputFile(sql, generateSQL(name, dbengine));

await fs.ensureFile(join(cwd, dir, 'db', 'development.sqlite3'));
await fs.ensureFile(join(cwd, dir, 'db', 'test.sqlite3'));
await fs.ensureFile(join(cwd, dir, 'db', 'production.sqlite3'));
fork icon36
star icon0
watch icon2

29
30
31
32
33
34
35
36
37
38
ipcRendererOn = (channel,listener) => ipcRenderer.on(channel, listener)
ipcRendererRemoveListener = (channel) => ipcRenderer.removeAllListeners(channel)
setOrgPath = (orgPath) => appRootPath = orgPath
outputJsonAsync = (fname, obj) => fse.outputFile(getAbsPath(fname),JSON.stringify(obj))
outputJsVarAsync = (fname, varName, obj) =>
                      fse.outputFile(getAbsPath(fname),"export var " +varName + " = " +JSON.stringify(obj))
outputFileAsync = (fname, data) => fse.outputFile(getAbsPath(fname),data)
readFileAsync = (fname, encoding) => fse.readFile(getAbsPath(fname),encoding)
readJsonAsync = fname => fse.readJSON(getAbsPath(fname))
readdirAsync = dirname => fse.readdir(getAbsPath(dirname))
fork icon1
star icon3
watch icon3

+ 5 other calls in file

41
42
43
44
45
46
47
48
49
50
51
52
  })
  return store.getQuads()
})


const createData = ({ path, data }) =>
  fs.outputFile(`./public${path.startsWith('/') ? path : '/' + path}`, data, err => err && console.error(err))


const getTurtleFiles = function (dirPath, arrayOfFiles) {
  const files = fs.readdirSync(dirPath)
  arrayOfFiles = arrayOfFiles || []
fork icon1
star icon1
watch icon0

765
766
767
768
769
770
771
772
773
774

// first, create a local temp folder
createTempFolder().then(({ path: dirPath, cleanupCallback }) => {
  const containerFolderPath = dirPath.substring(dirPath.lastIndexOf('/') + 1)

  fs.outputFile(`${dirPath}/${debugFileName}`, fileCode, isBinary ? 'base64' : undefined) // write file to that local temp folder
    .then(() => new Promise((resolve, reject) => {
      if (isBinary) { // if it is a zip action, unzip first
        extract(`${dirPath}/${debugFileName}`, { dir: `${dirPath}` }, function (err) {
          if (err) {
fork icon4
star icon0
watch icon3

+ 2 other calls in file

206
207
208
209
210
211
212
213
214
215
    let config = await prj.initialize({ checkDirs: true });
    if (config instanceof Error) {
        this.system(config);
        process.exit();
    }
    await fse.outputFile(path.join(options.root ? options.root : appPaths.root, 'ungic.config.json'), JSON.stringify(merge(this.config, config, { arrayMerge: (destinationArray, sourceArray) => _.union(destinationArray, sourceArray) }), null, 4));
} catch (e) {
    this.system(e);
    return
}
fork icon0
star icon2
watch icon1

+ 6 other calls in file

34
35
36
37
38
39
40
41
42
43
44
  trusted_host_pattern = trusted_host_pattern.replace(/\./g, '\.');
  trusted_host_pattern = `^${trusted_host_pattern}$`;
  
  await fs.outputFile('fleet/settings.local.php', await renderer('rancher_settings_php', {trusted_host_pattern}), 'utf-8');
  await fs.outputFile('fleet/main/fleet.yaml', await renderer('fleet_yaml'), 'utf-8');
  await fs.outputFile('fleet/main/rancher_values.yaml', await renderer('rancher_values_yaml', config), 'utf-8');
};


module.exports = {
  createRancherFiles,
fork icon0
star icon0
watch icon1

+ 11 other calls in file

34
35
36
37
38
39
40
41
42
43
const testPath = path.join(this.tempBase, `symlink-test-${comboOpts.platform}-${comboOpts.arch}`)
const testFile = path.join(testPath, 'test')
const testLink = path.join(testPath, 'testlink')

try {
  await fs.outputFile(testFile, '')
  await fs.symlink(testFile, testLink)
  this.canCreateSymlinks = true
} catch (e) {
  /* istanbul ignore next */
fork icon0
star icon0
watch icon0

+ 8 other calls in file

76
77
78
79
80
81
82
83
84
85
)
const nvueCompilerExists = fs.existsSync(nvueCompilerFilePath)

if (appJson.nvueCompiler === 'uni-app') {
  if (!nvueCompilerExists) {
    fsExtra.outputFile(nvueCompilerFilePath, '')
  }
} else {
  if (nvueCompilerExists) {
    fs.unlinkSync(nvueCompilerFilePath)
fork icon0
star icon0
watch icon1

246
247
248
249
250
251
252
253
254
255
  '[default]',
  'aws_access_key_id = my-old-profile-key',
  'aws_secret_access_key = my-old-profile-secret',
].join('\n');

await fse.outputFile(credentialsFilePath, credentialsFileContent);

await expect(
  runServerless({
    noService: true,
fork icon0
star icon0
watch icon961

+ 4 other calls in file

320
321
322
323
324
325
326
327
328
329
  @param {Object} info
  @return {Promise}
*/
async _writeFile(info) {
  if (!this.dryRun) {
    return fs.outputFile(info.outputPath, await info.render());
  }
},

/**
fork icon0
star icon0
watch icon159

function icon

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