How to use the outputFileSync function from fs-extra

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

The fs-extra.outputFileSync method writes data to a file and creates the file if it does not exist.

2538
2539
2540
2541
2542
2543
2544
2545
2546
2547

try {
    if (forceWrite || !this.lastWriteTimeLog || (Date.now() - this.lastWriteTimeLog > 60000)) {
        fs.outputFileSync('VlocityBuildLog.yaml', yaml.dump(logInfo, { lineWidth: 1000 }));
        fs.copySync('VlocityBuildLog.yaml', path.join(this.vlocity.tempFolder, 'logs', jobInfo.logName));
        fs.outputFileSync('VlocityBuildErrors.log', errorLog);
        this.lastWriteTimeLog = Date.now();
    }
} catch (e) {
    VlocityUtils.log(e);
fork icon82
star icon94
watch icon26

+ 51 other calls in file

694
695
696
697
698
699
700
701
702
703

} catch(err) {
  return callback(new Error('Fetch file from HTTP Service failed.'))
}

fs.outputFileSync(localFilePath, fileContent);

if (!fs.existsSync(localFilePath)) {
  return callback(new Error('Fetch file from HTTP Service failed.'))
}
fork icon34
star icon185
watch icon0

+ 6 other calls in file

How does fs-extra.outputFileSync work?

The fs-extra.outputFileSync method is part of the fs-extra module in Node.js, which provides additional functionality to the built-in fs module. The method takes two parameters: the path of the file to write to, and the data to write to the file. If the file does not exist, it is created. If the file does exist, its contents are overwritten with the new data. The method is synchronous, which means that it blocks the execution of any code after it until the write operation is complete. This makes it suitable for small files or situations where the code needs to wait for the file to be written before continuing. However, for large files or situations where performance is critical, it is recommended to use the asynchronous fs-extra.writeFile method instead. The fs-extra.outputFileSync method can also take an optional third parameter, which is an encoding to use when writing the file. The default encoding is 'utf8', but other options include 'ascii', 'utf16le', and 'base64', among others.

234
235
236
237
238
239
240
241
242
243
    )
}

const loader = p.join(buildDirectory, 'loader.js')
if (!fse.pathExistsSync(loader)) {
    fse.outputFileSync(
        loader,
        '// This file is required by Managed Runtime for historical reasons.\n'
    )
}
fork icon73
star icon177
watch icon16

+ 9 other calls in file

475
476
477
478
479
480
481
482
483
    VlocityUtils.log('- ' + allManifestByKey[key].VlocityDataPackKey + ' # ' + allManifestByKey[key].VlocityDataPackDisplayLabel);
    manifestArray.push(allManifestByKey[key].VlocityDataPackKey);
}

try {
    fs.outputFileSync('VlocityBuildLog.yaml', yaml.dump({ manifest: manifestArray }, { lineWidth: 1000 }));
} catch (e) {
    VlocityUtils.error('Error Writing Log', e);
}
fork icon80
star icon94
watch icon26

+ 53 other calls in file

Ai Example

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

// Write data to a file
fs.outputFileSync("example.txt", "Hello, world!");

// Append data to the same file
fs.outputFileSync("example.txt", "\nThis is a new line.", { flag: "a" });

In this example, the fs-extra module is imported and then the outputFileSync method is called twice. The first call writes the string "Hello, world!" to a file called "example.txt" in the current working directory. If the file does not exist, it will be created. If it does exist, its contents will be overwritten with the new data. The second call appends the string "\nThis is a new line." to the same file by passing an options object with the flag property set to 'a'. This tells the method to append the data to the end of the file instead of overwriting its contents.

3
4
5
6
7
8
9
10
11
12
13
14
15


module.exports = (fsObject = {}) => {
  const cwd = tempy.directory();


  Object.keys(fsObject).forEach((filename) => {
    fs.outputFileSync(path.join(cwd, filename), fsObject[filename]);
  });


  const createFileObject = (filename) => {
    return new Proxy({}, {
fork icon10
star icon59
watch icon42

53
54
55
56
57
58
59
60
61
62
63
64


function generateMarkdown(filePath, data) {
  if (!data) return
  if (!fs.pathExistsSync(filePath)) return
  const file = path.resolve(filePath, `${path.parse(source).name}.md`)
  fs.outputFileSync(file, data)
}


function setSeparate() {
  const splitLine = '-'.repeat(100)
fork icon0
star icon3
watch icon0

79
80
81
82
83
84
85
86
87
88
// Create the json object and write file to search-files dir
let json = {
  id: id,
  content: plainText,
};
fse.outputFileSync(contentPath, JSON.stringify(json));

// Update the in memory flexSearch indexes to be exported later
// All files (from all docsets) go into indexAll
indexAll.add(id, json.content);
fork icon6
star icon1
watch icon6

221
222
223
224
225
226
227
228
229
230
fs.ensureDirSync(temporaryOutputDir);

const identifier = files.exportUpload[0].originalFilename;
const inputXML = files.exportUpload[0].path;

fs.outputFileSync(join(uploadDir, "identifier.txt"), identifier, "utf-8");

const lastStatus = join(uploadDir, "status.txt");

const reportStatus = function (status) {
fork icon69
star icon0
watch icon23

+ 4 other calls in file

28
29
30
31
32
33
34
35
36
37
38
 * @param {object} obj
 */
const createYml = (obj) => {
    const yamlString = json2yaml.dump(obj, { lineWidth: -1 })
    const filePath = path.join(process.cwd(), 'config.yml')
    fse.outputFileSync(filePath, yamlString)
}


/**
 * @description: make sure download directory exists
fork icon0
star icon1
watch icon1

+ 6 other calls in file

56
57
58
59
60
61
62
63
64
65
        vendor = file === "vendor" ? res.css : vendor;
        general = file === "general" ? res.css : general;
        
        outputFileSync(`${dir}/general.css`, `${vendor}\n${general}`);
    } else {
        outputFileSync(`${dir}/${file}.css`, res.css);
    }
})
.catch(err => {
    grunt.log.subhead(`Postcss: ${dir}/${file}.css`);
fork icon0
star icon0
watch icon1

+ 3 other calls in file

28
29
30
31
32
33
34
35
36
37
if (dest.indexOf('array.wxs') !== -1) {
  // 兼容 Array.isArray
  const content = fs.readFileSync(dest, 'utf8').toString()
    .replace('array && array.constructor === \'Array\'',
      'array && (array.constructor === \'Array\' || (typeof Array !== \'undefined\' && Array.isArray(array)))')
  fs.outputFileSync(dest, content)
} else if (dest.indexOf('notify/notify.js') !== -1) {
  // notify.js show 方法与 show 属性冲突
  const content = fs.readFileSync(dest, 'utf8').toString()
    .replace('show()', 'showNotify()')
fork icon0
star icon0
watch icon1

+ 2 other calls in file

169
170
171
172
173
174
175
176
177
178
  '[my-other-profile]',
  'aws_access_key_id = my-other-profile-key',
  'aws_secret_access_key = my-other-profile-secret',
].join('\n');

fse.outputFileSync(credentialsFilePath, newCredentialsFileContent);

return awsConfigCredentials.configureCredentials().then(() => {
  const UpdatedCredentialsFileContent = fs.readFileSync(credentialsFilePath).toString();
  const lineByLineContent = UpdatedCredentialsFileContent.split('\n');
fork icon0
star icon0
watch icon961

+ 14 other calls in file

338
339
340
341
342
343
344
345
346
347
      return output.length;
    }
  };

  if (_this.opts.writeToFileEmit) {
    fse.outputFileSync(outputFile, output);
  }
}

if (compiler.hooks) {
fork icon0
star icon0
watch icon1

+ 10 other calls in file

147
148
149
150
151
152
153
154
155
156

it('_removeLinks', function () {
  // This is our package that is linked in.
  let srcDir = path.join(process.cwd(), 'tmp', 'beta');
  expect(dir(srcDir)).to.not.exist;
  fs.outputFileSync(path.join(srcDir, 'package.json'), 'beta');
  expect(file(path.join(srcDir, 'package.json'))).to.contain('beta');

  // This is the directory we got "back" from `PackageCache.create`.
  let targetDir = path.join(process.cwd(), 'tmp', 'target');
fork icon0
star icon0
watch icon159

+ 3 other calls in file

322
323
324
325
326
327
328
329
330
331
process.chdir(originalWorkingDirectory);

this._conf.set(label, outputDir);

let outputFile = path.join(outputDir, translate(type, 'manifest'));
fs.outputFileSync(outputFile, manifest);

// Remove any existing yarn.lock file so that it doesn't try to incorrectly use it as a base.
if (type === 'yarn') {
  try {
fork icon0
star icon0
watch icon159

146
147
148
149
150
151
152
153
154
155
console.log(TEMPLATE_FOLDERS);
TEMPLATE_FOLDERS.forEach((TEMPLATE_FOLDER) => {
  const files = find.fileSync(TEMPLATE_FILENAME_PATTERN, TEMPLATE_FOLDER);
  files.forEach(function (file) {
    const destFile = file.split(".template")[0].substr(TEMPLATE_FOLDER.length);
    fs.outputFileSync(
      destFile,
      fs
        .readFileSync(file, "utf8")
        .replace(appNameToken, appName)
fork icon0
star icon0
watch icon1

+ 2 other calls in file

53
54
55
56
57
58
59
60
61
62

if (fs.existsSync(lockFilePath)) {
   return;
}

fs.outputFileSync(lockFilePath, '', { flag: 'w+' });

logger.info(`Created lockfile ${lockFilePath}`);

const onExitHandler = () => {
fork icon0
star icon0
watch icon0

+ 3 other calls in file

187
188
189
190
191
192
193
194
195
196
        }
    } else {
        // update version.json
        fs.outputJsonSync(path.resolve(dest, 'version.json'), newVersionContent);
        // update latest_version.txt
        fs.outputFileSync(path.resolve(dest, 'latest_version.txt'), uuid);
    }
}

const outputPath = path.resolve(dest, uuid);
fork icon0
star icon0
watch icon0

function icon

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