How to use the readFile function from fs

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

50
51
52
53
54
55
56
57
58
59
charset = (charset || 'utf-8').toLowerCase();
var opt = {encoding: charset};
if (charset !== 'utf-8') {
    opt.encoding = null;
}
fs.readFile(file, opt, function (err, data) {
    if (!!err) {
        console.error(err);
        callback([
            util.format(
fork icon124
star icon815
watch icon42

+ 30 other calls in file

330
331
332
333
334
335
336
337
338
339
var t = this;
var className = this.__className;
t.__fatalCompileError = false;
t.__numClassesDefined = 0;

fs.readFile(
  this.getSourcePath(),
  { encoding: "utf-8" },
  function (err, src) {
    if (err) {
fork icon257
star icon757
watch icon77

20
21
22
23
24
25
26
27
28
29
* fs.link(): 新建指向文件的硬链接。
* fs.mkdir(): 新建文件夹。
* fs.mkdtemp(): 创建临时目录。
* fs.open(): 设置文件模式。
* fs.readdir(): 读取目录的内容。
* fs.readFile(): 读取文件的内容。相关方法:fs.read()。
* fs.readlink(): 读取符号链接的值。
* fs.realpath(): 将相对的文件路径指针(.、..)解析为完整的路径。
* fs.rename(): 重命名文件或文件夹。
* fs.rmdir(): 删除文件夹。
fork icon192
star icon570
watch icon16

+ 11 other calls in file

404
405
406
407
408
409
410
411
412
413
});

t.test('.render', function(t) {
    var options = {
        request: function(req, callback) {
            fs.readFile(path.join(__dirname, '..', req.url), function(err, data) {
                callback(err, { data: data });
            });
        },
        ratio: 1
fork icon170
star icon562
watch icon36

132
133
134
135
136
137
138
139
140
141
MySQLStore.prototype.createDatabaseTable = function() {
	return Promise.resolve().then(() => {
		debug.log('Creating sessions database table');
		const fs = require('fs').promises;
		const schemaFilePath = path.join(__dirname, 'schema.sql');
		return fs.readFile(schemaFilePath, 'utf-8').then(sql => {
			sql = sql.replace(/`[^`]+`/g, '??');
			const params = [
				this.options.schema.tableName,
				this.options.schema.columnNames.session_id,
fork icon100
star icon300
watch icon14

307
308
309
310
311
312
313
314
315
316
```js
const http = require('http');
const fs = require('fs');

http.createServer((req, res) => {
  fs.readFile(`${__dirname}/index.html`, (err, data) => {
    if (err) {
      res.statusCode = 500;
      res.end(String(err));
      return;
fork icon76
star icon294
watch icon11

335
336
337
338
339
340
341
342
343
344
fs.stat(chatsPath+dir_name+"/"+request.body.file_name+".jsonl", function(err, stat) {
    
    if (err === null) {
        
        if(stat !== undefined){
            fs.readFile(chatsPath+dir_name+"/"+request.body.file_name+".jsonl", 'utf8', (err, data) => {
                if (err) {
                  console.error(err);
                  response.send(err);
                  return;
fork icon60
star icon276
watch icon17

+ 5 other calls in file

492
493
494
495
496
497
498
499
500
501
  assert.strictEqual(err.code, 'ENOENT');
  assert.strictEqual(err.syscall, 'open');
  return true;
};

fs.readFile(nonexistentFile, common.mustCall(validateError));

assert.throws(
  () => fs.readFileSync(nonexistentFile),
  validateError
fork icon42
star icon19
watch icon0

58
59
60
61
62
63
64
65
66
67
}
// todo list has a head
let file = files[0];

// get the contents of the file
fs.readFile(path + '/' + file, 'utf8', (err, text) => {
    // process all relevant data
    let entry = make_entry(text);
    if (entry != undefined) {
        entry.name = file;
fork icon6
star icon60
watch icon6

59
60
61
62
63
64
65
66
67
68
const read = (location) => readFileSync(location, 'utf-8')
// write file
const write = (location) => (content) => writeFileSync(location, content)
const readAsync = (location) =>
  new Promise((resolve, reject) => {
    readFile(location, 'utf-8', (err, data) => {
      if (err) {
        reject(err)
      }
      resolve(data)
fork icon5
star icon18
watch icon3

+ 19 other calls in file

107
108
109
110
111
112
113
114
115
116

### 2. Promise
```js
function readFileAsync(path){
  return new Promise((resolve, reject) => {
    fs.readFile(path, (err, data) => {
      if(err) reject(err)
      else resolve(data)
    })
  })
fork icon12
star icon14
watch icon0

+ 3 other calls in file

44
45
46
47
48
49
50
51
52
53
                } else {
                        resolve([...data])
                }
        })
} else {
        fs.readFile(path, {encoding: 'utf8'}, function (error, data) {
                if (error) {
                        reject(error)
                } else {
                        resolve(data)
fork icon4
star icon19
watch icon7

+ 23 other calls in file

205
206
207
208
209
210
211
212
213
214
fs.exists(path, (exists: boolean) => {
    if (!exists) {
        rej();
    }

    fs.readFile(path, (error, buffer) => {
        if (error) {
            rej(error);
            return;
        }
fork icon1
star icon12
watch icon3

36
37
38
39
40
41
42
43
44
45
const renameAsync = (oldPath, newPath) => new Promise((resolve, reject) => {
    return fs.rename(oldPath, newPath, (err) => err ? reject(err) : resolve())
});

/**
 * Promisified version of fs.readFile
 * 
 * @method readFileAsync
 * 
 * @param {string} path
fork icon7
star icon10
watch icon3

+ 3 other calls in file

78
79
80
81
82
83
84
85
86
87
    mtime: statz.mtime
}, function(err, handle) {
    if (err) {
        cb(err);
    } else {
        fs.readFile(localfile, function(err, data) {
            if (err) {
                cb(err);
            } else {
                if (data.length === 0) {
fork icon7
star icon11
watch icon0

367
368
369
370
371
372
373
374
375
376
377
378
}


function loadConfig(callback) {
  makeConfigDir(function(err) {
    if (err) return callback(err);
    fs.readFile(configFile, {encoding: 'utf8'}, function(err, text) {
      var json;


      if (text && text.length > 0) {
        try {
fork icon14
star icon8
watch icon15

+ 3 other calls in file

207
208
209
210
211
212
213
214
215
216
    'Content-Type': mimeType || 'text/plain'
  })
  res.write(buffer, 'binary')
  res.end()
} else {
  sysFS.readFile(realFilePath, (err, buffer) => {
    if (err) {
      res.writeHead(500, {
        'content-type': 'text/plain'
      })
fork icon2
star icon11
watch icon11

116
117
118
119
120
121
122
123
124
125
function _transform(txt){
  if(!module) return txt;
  return module.transform.Apply(txt, fname);
}

if(cb) fread = function(fread_cb){ fs.readFile(fname, 'utf8', fread_cb); };
else fread = function(fread_cb){ return fread_cb(null, fs.readFileSync(fname, 'utf8'));  };
return fread(function(err, data){
  if(err){
    if(cb) return cb(err);
fork icon5
star icon5
watch icon2

231
232
233
234
235
236
237
238
239
        fs.readFile(__dirname + "/pages/index.html").then(contents => res.end(contents));
    else {
        //We use .then() and .catch() b/c fs.promises is async.
        fs.access(__dirname + "/pages" + req.url + ".html", fsc.F_OK)
        .then(() => fs.readFile(__dirname + "/pages" + req.url + ".html").then(contents => res.end(contents)))
        .catch(() => fs.readFile(__dirname + "/pages/404.html").then(contents => res.end(contents)));
    }
    
}
fork icon1
star icon3
watch icon4

+ 8 other calls in file

44
45
46
47
48
49
50
51
52
53
if (isBlocked) return
if (!isOwner) return

switch (command) {
    case 'y': case 'yes':
        fs.readFile(`temp/to-${senderid}.txt`, 'utf8', function(err, mto) {
            if (err) throw err;
            if (mto == "Restricted command detected, continue (Y/N)?") {
                fs.readFile(`temp/from-${senderid}.txt`, 'utf8', function(err, mfrom) {
                    if (err) throw err;
fork icon1
star icon3
watch icon0

+ 7 other calls in file