How to use the writeFileAsync function from fs-extra

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

fs-extra.writeFileAsync is a function in the fs-extra package that writes data to a file asynchronously.

129
130
131
132
133
134
135
136
137
138
  const folder_path = path.join(store.get('itemset_path'), data.champ, 'Recommended');
  const file_path = path.join(folder_path, `CIFY_${data.champ}_${data.source}_${data.file_prefix}.json`);

  return fs.mkdirsAsync(folder_path)
    .catch(err => Log.warn(err))
    .then(() => fs.writeFileAsync(file_path, itemset_data, 'utf8'))
    .catch(err => {
      throw new ChampionifyErrors.FileWriteError('Failed to write item set json file').causedBy(err);
    });
});
fork icon169
star icon0
watch icon2

175
176
177
178
179
180
181
182
183
184
    author: pkg.author,
    description: pkg.description,
    electron_version: pkg.dependencies['electron']
  };
  fs.mkdirsSync(path.join(__dirname, '../dev/'));
  return fs.writeFileAsync(path.join(__dirname, '../dev/package.json'), JSON.stringify(package_json, null, 2), 'utf8');
});

gulp.task('electron:download:mac', function(cb) {
  return cache('darwin', 'x64', cb);
fork icon169
star icon0
watch icon2

How does fs-extra.writeFileAsync work?

fs-extra.writeFileAsync is a function provided by the fs-extra module that writes data to a file asynchronously, replacing the file if it already exists, and creating the file if it doesn't exist. It returns a Promise that resolves with no value when the write operation is complete.

98
99
100
101
102
103
104
105
106
107
          });
  })
  .then(function()
  {
      // Write the generated include string to Plugins.h
      return fs.writeFileAsync(path.join(stagedSketchDir, 'Plugins.h'), pluginString);
  });
})
.then( function()
{
fork icon94
star icon63
watch icon33

+ 2 other calls in file

191
192
193
194
195
196
197
198
199
200
    }

    xml = replaceTextBetween(xml, XML_START_PLUGINS_MANIFEST, XML_END_PLUGINS_MANIFEST, manifestXmlManifestStr);
    xml = replaceTextBetween(xml, XML_START_PLUGINS_ACTIVITY, XML_END_PLUGINS_ACTIVITY, manifestXmlActivityStr);
    xml = replaceTextBetween(xml, XML_START_PLUGINS_APPLICATION, XML_END_PLUGINS_APPLICATION, manifestXmlApplicationStr);
    return fs.writeFileAsync(manifestXml, xml, 'utf-8');
  } else {
    logger.log('No plugin XML to inject');
  }
});
fork icon22
star icon14
watch icon49

Ai Example

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

async function writeToFile() {
  try {
    await fse.writeFileAsync("example.txt", "Hello, world!");
    console.log("File written successfully.");
  } catch (err) {
    console.error(err);
  }
}

writeToFile();

In this example, fs-extra is first imported into the file. Then, a function called writeToFile() is defined which uses await to write the string "Hello, world!" to a file called example.txt. The function also logs a success message to the console if the file is written successfully. Finally, the writeToFile() function is called to run the code.

103
104
105
106
107
108
109
110
111
112
      encoding: null,
    })
    if (response.statusCode != 200) {
      throw new Error(`Response status code ${response.statusCode}`)
    }
    await fs.writeFileAsync(destPath, body)
    log(`Successfully downloaded to ${destPath}`)
  }
  return destPath
}
fork icon356
star icon0
watch icon1

43
44
45
46
47
48
49
50
51
52
  fs.readFileAsync('./node_modules/brace/theme/tomorrow_night.js', 'utf8'),
  fs.readFileAsync('./node_modules/brace/mode/markdown.js', 'utf8')
]).then(items => {
  console.info(colors.white('      ace.js'))
  let result = uglify.minify(items.join(';\n'), { output: { 'max_line_len': 1000000 } })
  return fs.writeFileAsync('./assets/js/ace/ace.js', result.code)
}),
// Modes
fs.readdirAsync('./node_modules/brace/mode').then(modeList => {
  return Promise.map(modeList, mdFile => {
fork icon0
star icon1
watch icon4

+ 3 other calls in file

68
69
70
71
72
73
74
75
76
77
for (let profile in cachedItems) {
    for (let name in cachedItems[profile]) {
        let cacheFile = path.join(this._options.cachePath, profile, name);
        let dirPath = path.dirname(cacheFile);
        promises.push(fs.mkdirpAsync(dirPath).then(() => {
            return fs.writeFileAsync(cacheFile, cachedItems[profile][name]).then(() => {
                this._logger.debug('Local cache file %s written.', cacheFile);
            });
        }))
    }
fork icon0
star icon1
watch icon1

300
301
302
303
304
305
306
307
308
309
    return false;
  }
},
async saveConfig() {
  let fs = require('fs-extra');
  fs.writeFileAsync(syzoj.configDir, JSON.stringify(syzoj.configInFile, null, 2));
},
withTimeoutRetry(func) {
  let attemptCount = 0;
  return new Promise((resolve, reject) => {
fork icon0
star icon0
watch icon1

+ 21 other calls in file

225
226
227
228
229
230
231
232
233
234
.then(function (buffer) {
  var data = buffer.toString();
  data = data.replace(/\s*<file url="file:\/\/\$PROJECT_DIR\$\/(server|api)" libraries="{shang-auto-generate}" \/>\n/g, '');
  data = data.replace(/,\s*shang-auto-generate/gi, '');
  data = data.replace(`<component name="JavaScriptLibraryMappings">`, `<component name="JavaScriptLibraryMappings">\n    <file url="file://$PROJECT_DIR$/${typingScope}" libraries="{shang-auto-generate}" />\n`);
  return fs.writeFileAsync(jsLibraryMappingsXmlPath, data);
})
.then(function () {
  return fs.mkdirAsync(librariesPath)
    .catch(function () {
fork icon0
star icon0
watch icon0

+ 27 other calls in file

83
84
85
86
87
88
89
90
91
92
      encoding: null,
    });
    if (response.statusCode !== 200) {
      log(`Response status code ${response.statusCode}`);
    }
    await fs.writeFileAsync(destPath, body);
    log(`Successfully downloaded to ${destPath}`);
  }
  return destPath;
};
fork icon0
star icon0
watch icon2

+ 3 other calls in file

59
60
61
62
63
64
65
66
67
68
  // If the contents have changed, save the file
  // (otherwise do nothing to skip a page refresh by Ionic)
  if (typeScriptLocale && typeScriptLocale == newTypeScriptLocale) {
    console.log(`${chalk.green(path.relative(rootDir, typeScriptLocaleFile))} has not changed`);
  } else {
    return fs.writeFileAsync(typeScriptLocaleFile, newTypeScriptLocale, { encoding: 'utf8' }).then(() => {
      console.log(`${chalk.yellow(path.relative(rootDir, localeFile))} -> ${chalk.green(path.relative(rootDir, typeScriptLocaleFile))}`);
    });
  }
}));
fork icon0
star icon0
watch icon4

function icon

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