How to use the readFile function from fs-extra

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

250
251
252
253
254
255
256
257
258
259
debugData.indexOf(`info: [${loggerName}]: Test logger - info`).should.be.greaterThan(0);
debugData.indexOf(`debug: [${loggerName}]: Test logger - debug`).should.be.greaterThan(0);
debugData.indexOf('Successfully constructed a winston logger with configurations').should.be.greaterThan(0);

// read the error file
const errorData = await fs.readFile(errorFilePath);
// error file should only contain errors
errorData.indexOf(`error: [${loggerName}]: Test logger - error`).should.be.greaterThan(0);
errorData.indexOf('Test logger - warn').should.equal(-1);
errorData.indexOf('Test logger - info').should.equal(-1);
fork icon522
star icon768
watch icon62

+ 27 other calls in file

276
277
278
279
280
281
282
283
284
285
286
287
    await updateBuildNumber();
});


async function updateBuildNumber() {
    // Edit the version number from the package.json
    const packageJsonContents = await fs.readFile('package.json', 'utf-8');
    const packageJson = JSON.parse(packageJsonContents);


    // Change version number
    // 3rd part of version is limited to Max Int32 numbers (in VSC Marketplace).
fork icon209
star icon952
watch icon42

+ 5 other calls in file

144
145
146
147
148
149
150
151
152
153
154
155
  }
]


async function readFileIfExists (path) {
  if (await fse.exists(path)) {
    return await fse.readFile(path, 'utf8')
  }
}


async function getHomeHandler (req, res) {
fork icon234
star icon281
watch icon77

+ 5 other calls in file

82
83
84
85
86
87
88
89
90
91
        file.path = file.path.slice(0, file.path.length - 10) + '.js'
        next(bundleError, file)
      })
    )
} else {
  fs.readFile(file.path, 'UTF-8').then((contents) => {
    file.contents = Buffer.from(contents)
    next(null, file)
  })
}
fork icon38
star icon137
watch icon7

+ 4 other calls in file

59
60
61
62
63
64
65
66
67
68
69
70
        .on('error', done)
        .pipe(sink())
    )


function loadSampleUiModel (src) {
  return fs.readFile(ospath.join(src, 'ui-model.yml'), 'utf8').then((contents) => yaml.safeLoad(contents))
}


function registerPartials (src) {
  return vfs.src('partials/*.hbs', { base: src, cwd: src }).pipe(
fork icon38
star icon137
watch icon7

+ 4 other calls in file

125
126
127
128
129
130
131
132
133
134
    () => {},
  ...get(config, 'build.postcss.plugins', [])
]

if (userFileExists) {
  css = await fs.readFile(path.resolve(userFilePath), 'utf8') + css

  toProcess.unshift(
    postcssImport({path: path.dirname(userFilePath)})
  )
fork icon31
star icon876
watch icon7

175
176
177
178
179
180
181
182
183
184
185
 * @param {string} savePath - Path to the Factorio save to patch.
 * @param {Array<Object>} modules - Description of the modules to patch.
 * @memberof module:lib/factorio
 */
async function patch(savePath, modules) {
	let zip = await JSZip.loadAsync(await fs.readFile(savePath));
	let root = zip.folder(findRoot(zip));


	let patchInfoFile = root.file("clusterio.json");
	let patchInfo;
fork icon58
star icon228
watch icon0

+ 3 other calls in file

3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
});

let htmlFileContent = [];
for (let i in allRetrievedLwcHtmlFiles) {
    if (fs.existsSync(allRetrievedLwcHtmlFiles[i])) {
        htmlFileContent.push(await fs.readFile(allRetrievedLwcHtmlFiles[i], 'utf8'));
    }
}

let deployments = {
fork icon82
star icon94
watch icon0

+ 3 other calls in file

106
107
108
109
110
111
112
113
114
115
  )
);

// check if file exists
if (fs.existsSync(path.join(process.cwd(), config.modes.window.icon))) {
  const iconFile = await fs.readFile(
    path.join(process.cwd(), config.modes.window.icon)
  );
  icns.addFromPng(iconFile, ["ic09"], raw);
  // icns.addFromPng(iconFile, ['ic07'], raw);
fork icon15
star icon187
watch icon0

3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380


DataPacksJob.prototype.downloadPerformanceData = async function (jobInfo) {
    var existingRecords = [];
    var lastTimeStamp = "";
    if (fs.existsSync(jobInfo.projectPath)){
        existingRecords = JSON.parse(await fs.readFile(jobInfo.projectPath,'utf-8'));
        lastTimeStamp = JSON.parse(existingRecords[0]).Timestamp;
    }


    return new Promise(async (resolve, reject) => {
fork icon80
star icon94
watch icon26

+ 17 other calls in file

418
419
420
421
422
423
424
425
426
});

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));
  }
fork icon7
star icon86
watch icon2

+ 51 other calls in file

170
171
172
173
174
175
176
177
178
179
180
	return process && process.platform === 'darwin';
};


toolUtils.insertContentIntoFile = async function(filePath, markerOpen, markerClose, contentToInsert) {
	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);
fork icon8
star icon43
watch icon13

+ 17 other calls in file

425
426
427
428
429
430
431
432
433
434

const currPath = imageDiffError.currImg.path;
const refPath = imageDiffError.refImg.path;

const [currBuffer, refBuffer] = await Promise.all([
    fs.readFile(currPath),
    fs.readFile(refPath)
]);

const hash = createHash(currBuffer) + createHash(refBuffer);
fork icon38
star icon39
watch icon5

+ 5 other calls in file

200
201
202
203
204
205
206
207
208
209
210
211


  await fs.writeFile(sysPath.join(root, "next.config.js"), content);
};


const migrateTailwindToStyled = async (root, rootFolder) => {
  const indexTailwindCss = await fs.readFile(
    sysPath.join(root, `app/global.css`)
  );
  const compiled = await compilePostCss(indexTailwindCss.toString(), root);
  const baseCss = await compilePostCss("@tailwind base;", root).css;
fork icon5
star icon36
watch icon2

+ 5 other calls in file

191
192
193
194
195
196
197
198
199
200
const run = async (dir, sidebar) => {
  for await (const x of walk(dir)) {
    if (x.endsWith('.png') || x.endsWith('.jpeg') || x.endsWith('.jpg')) {
      fs.copy(x, path.resolve('./src/build/assets', path.basename(x)));
    } else if (x.endsWith('.md')) {
      fs.readFile(x, 'utf8', (err, file) => {
        const graymatter = matter(file);
        const frontmatter = graymatter.data;
        if (!frontmatter || !frontmatter.permalink) {
          // console.warn('Skipping ' + x + ': no frontmatter permalink.');
fork icon11
star icon33
watch icon0

+ 9 other calls in file

2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
 * @returns {Promise<Uint8Array>} The bytes of the output document (for filesystem save).
 */
async function mergePDFFiles(files, metadata = null) {
  const outputDocument = await PDFDocument.create();
  for (let i = 0, n = files.length; i < n; i += 1) {
    const fileData = await fs.readFile(files[i]);
    const filePDF = await PDFDocument.load(fileData);
    const filePages = await outputDocument.copyPages(filePDF, filePDF.getPageIndices());
    for (let j = 0, k = filePages.length; j < k; j += 1) {
      outputDocument.addPage(filePages[j]);
fork icon8
star icon11
watch icon6

+ 29 other calls in file

172
173
174
175
176
177
178
179
180
181
    if (stats.size > config.defaultLimits.attachmentIndexed) {
      warning = 'Pièce jointe trop volumineuse pour être analysée'
    } else {
      item._attachment_url = `${config.publicUrl}/api/v1/datasets/${dataset.id}/attachments/${flatItem[attachmentField.key]}`
      if (!attachmentField['x-capabilities'] || attachmentField['x-capabilities'].indexAttachment !== false) {
        item._file_raw = (await fs.readFile(filePath)).toString('base64')
      }
    }
  }
}
fork icon6
star icon26
watch icon4

+ 13 other calls in file

824
825
826
827
828
829
830
831
832
833
}

// Ensure `/.homeybuild` is added to `.gitignore`, if it exists
const gitIgnorePath = path.join(this.path, '.gitignore');
if (await fse.pathExists(gitIgnorePath)) {
  const gitIgnore = await fse.readFile(gitIgnorePath, 'utf8');
  if (!gitIgnore.includes('.homeybuild')) {
    Log(colors.green('✓ Automatically added `/.homeybuild/` to .gitignore'));
    await fse.writeFile(gitIgnorePath, `${gitIgnore}\n\n# Added by Homey CLI\n/.homeybuild/`);
  }
fork icon4
star icon5
watch icon4

2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
    next();
});
this.app.use('/info', async function(req,res,next){
    if(req.path.endsWith('.md')){
        var fileName=__dirname+'/../public-docs/'+req.path;
        var content = await fs.readFile(fileName,'utf8');
        var md = await markdownRender('html', content);
        MiniTools.serveText(md.content, 'html')(req,res);
    }else{
        serveContent(__dirname+'/../docs',be.optsGenericForFiles(req))(req,res,next);
fork icon3
star icon4
watch icon10

+ 47 other calls in file

582
583
584
585
586
587
588
589
590
591
if (!remoteLinks[linksSelfLocation]) {
  const real = await fs.realpath(process.argv[1])
  if (real.endsWith("node_modules/kontinuous/bin/kontinuous")) {
    // npx or packages.json/dependencies
    const packageFile = `${path.dirname(real)}/../package.json`
    const packageJSON = await fs.readFile(packageFile, {
      encoding: "utf-8",
    })
    const packageDef = JSON.parse(packageJSON)
    remoteLinks[
fork icon0
star icon7
watch icon5

+ 5 other calls in file

function icon

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