How to use the readFileSync function from fs

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

fs.readFileSync is a method in the Node.js fs module that reads and returns the contents of a file synchronously.

11
12
13
14
15
16
17
18
19
20
 * @param  {string} file - absolute file path
 * @return {array}  raw content of file
 */
exports.raw = function (file) {
    try {
        return fs.readFileSync(file.split(/[?#]/)[0]);
    } catch (ex) {
        return null;
    }
};
fork icon124
star icon815
watch icon42

+ 92 other calls in file

32
33
34
35
36
37
38
39
40
41

await step(`1. cleanup output folder`, async () => {
  let cnameText = null;
  const cnamePath = path.join(DST_PATH, 'CNAME');
  if (fs.existsSync(cnamePath))
    cnameText = fs.readFileSync(cnamePath, 'utf8');
  await rmAsync(DST_PATH);
  fs.mkdirSync(DST_PATH);
  if (cnameText)
    fs.writeFileSync(cnamePath, cnameText, 'utf8');
fork icon69
star icon796
watch icon14

+ 31 other calls in file

How does fs.readFileSync work?

fs.readFileSync is a synchronous method that takes two arguments: the path of the file to read, and an optional object that specifies how to read the file. It returns the contents of the file as a Buffer object or a string, depending on the encoding specified in the options object. When called, fs.readFileSync first checks whether the file at the specified path exists and can be read. If the file cannot be read, the method throws an error. If the file can be read, the method reads the entire contents of the file into memory and returns it as a Buffer object or a string. Here is the syntax of the fs.readFileSync method: css Copy code {{{{{{{ class="!whitespace-pre hljs language-css">fs.readFileSync(path[, options]) The path argument is a string that specifies the path of the file to read. The options argument is an optional object that specifies how to read the file. It can include the following properties: encoding: A string that specifies the character encoding to use when reading the file. If not specified, the method returns a Buffer object. Common encodings include 'utf8', 'ascii', and 'binary'. flag: A string that specifies the file system flag to use when opening the file. The default value is 'r', which opens the file for reading. Here's an example of using fs.readFileSync to read the contents of a file: arduino Copy code {{{{{{{ class="!whitespace-pre hljs language-arduino">const fs = require('fs'); // Read the contents of a text file as a string const contents = fs.readFileSync('/path/to/file.txt', 'utf8'); // Read the contents of a binary file as a Buffer const buffer = fs.readFileSync('/path/to/image.jpg'); In this example, we first require the built-in fs module. We then call fs.readFileSync twice: once to read the contents of a text file as a string, and once to read the contents of a binary file as a Buffer object. Note that fs.readFileSync is a synchronous method, which means that it blocks the execution of the Node.js process until the file has been read completely. This can cause performance issues if used on large files or if called frequently. In general, it is better to use the asynchronous fs.readFile method instead, which allows other operations to run while the file is being read.

58
59
60
61
62
63
64
65
66
67

~~~js
const fs = require('fs')

try {
  const data = fs.readFileSync('/tmp/flydean.txt', 'utf8')
  console.log(data)
} catch (err) {
  console.error(err)
}
fork icon191
star icon570
watch icon16

+ 5 other calls in file

191
192
193
194
195
196
197
198
199
200
```js
// 生成 data URI
const fs = require('fs');
const mime = 'image/png';
const encoding = 'base64';
const base64Data = fs.readFileSync(`${__dirname}/monkey.png`).toString(encoding);
const uri = `data:${mime};${encoding},${base64Data}`;
console.log(uri);

// data URI 转文件
fork icon76
star icon294
watch icon11

Ai Example

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

// Read the contents of a file as a string
const contents = fs.readFileSync("/path/to/file.txt", "utf8");

console.log(contents);

In this example, we require the built-in fs module and then call the fs.readFileSync method with two arguments: the path of the file to read (/path/to/file.txt) and the encoding to use when reading the file ('utf8'). The fs.readFileSync method returns the contents of the file as a string, which we then log to the console using console.log. Note that the contents variable will contain the entire contents of the file as a single string, including any line breaks or other special characters.

538
539
540
541
542
543
544
545
546
547
      "externalAdReply": {
         "title": `Selamat ${salam} ${pushname}`,
         "body": `© ${ownername}`,
         "previewType": "PHOTO",
         "thumbnailUrl": ``,
         "thumbnail": fs.readFileSync(thumbnail),
         "sourceUrl": `${myweb}`
      }
   }
}, {
fork icon332
star icon109
watch icon0

70
71
72
73
74
75
76
77
78
79
let aborted = false;
const messages = [];

if (TARGET === "WP" && !IS_PRODUCTION) {
  const filePath = path.resolve(paths.build, "../../../brizy.php");
  const fileContents = fs.readFileSync(filePath, "utf-8");
  const r = /define\s*\(\s*("|')BRIZY_DEVELOPMENT\1,\s*false\s*\)/gm;

  if (r.test(fileContents)) {
    aborted = true;
fork icon76
star icon256
watch icon0

+ 3 other calls in file

72
73
74
75
76
77
78
79
80
81
exports.read = co.promisify(fs.read);
exports.readSync = fs.readSync;
exports.readdir = co.promisify(fs.readdir);
exports.readdirSync = fs.readdirSync;
exports.readFile = co.promisify(fs.readFile);
exports.readFileSync = fs.readFileSync;
exports.readlink = co.promisify(fs.readlink);
exports.readlinkSync = fs.readlinkSync;
exports.realpath = co.promisify(fs.realpath);
exports.realpathSync = fs.realpathSync;
fork icon22
star icon45
watch icon26

179
180
181
182
183
184
185
186
187
188
⋆ من فضلك التزم بالقوانين..`
let buttons = [
{buttonId: `wkwwk`, buttonText: {displayText: 'نورت الجروب يحب♥✨'}, type: 1}
]
let buttonMessage = {
document: fs.readFileSync('./XeonMedia/theme/cheems.xlsx'),
mimetype: docs,
jpegThumbnail:XeonWlcm,
mentions: [num],
fileName: `${metadata.subject}`,
fork icon143
star icon4
watch icon2

244
245
246
247
248
249
250
251
252
253

```
exports.imageUrl = () => {
    const mime = 'image/png'
    const encoding = 'base64'
    const base64Data = fs.readFileSync(`${__dirname}/image.png`).toString(encoding)
    const uri = `data:${mime};${encoding},${base64Data}`
    // data:image/png;base64,
    fs.writeFileSync(`${__dirname}/index.html`,`<img src='${uri}' />`)
    // console.log(uri)
fork icon141
star icon308
watch icon22

182
183
184
185
186
187
188
189
190
191
   //you fail to put, i sue you for sure!
let buttons = [
{buttonId: `wkwwk`, buttonText: {displayText: 'نورت الزريبه😂'}, type: 1}
]
let buttonMessage = {
document: fs.readFileSync('./KhufuMedia/theme/cheems.xlsx'),
mimetype: docs,
jpegThumbnail:khufuWlcm,
mentions: [num],
fileName: `${metadata.subject}`,
fork icon77
star icon3
watch icon1

+ 3 other calls in file

17
18
19
20
21
22
23
24
25
26
27
const qsRegex = '(?:p(?:ass)?w(?:or)?d|pass(?:_?phrase)?|secret|(?:api_?|private_?|public_?|access_?|secret_?)key(?:_?id)?|token|consumer_?(?:id|key|secret)|sign(?:ed|ature)?|auth(?:entication|orization)?)(?:(?:\\s|%20)*(?:=|%3D)[^&]+|(?:"|%22)(?:\\s|%20)*(?::|%3A)(?:\\s|%20)*(?:"|%22)(?:%2[^2]|%[^2]|[^"%])+(?:"|%22))|bearer(?:\\s|%20)+[a-z0-9\\._\\-]+|token(?::|%3A)[a-z0-9]{13}|gh[opsu]_[0-9a-zA-Z]{36}|ey[I-L](?:[\\w=-]|%3D)+\\.ey[I-L](?:[\\w=-]|%3D)+(?:\\.(?:[\\w.+\\/=-]|%3D|%2F|%2B)+)?|[\\-]{5}BEGIN(?:[a-z\\s]|%20)+PRIVATE(?:\\s|%20)KEY[\\-]{5}[^\\-]+[\\-]{5}END(?:[a-z\\s]|%20)+PRIVATE(?:\\s|%20)KEY|ssh-rsa(?:\\s|%20)*(?:[a-z0-9\\/\\.+]|%2F|%5C|%2B){100,}'


function maybeFile (filepath) {
  if (!filepath) return
  try {
    return fs.readFileSync(filepath, 'utf8')
  } catch (e) {
    return undefined
  }
}
fork icon241
star icon447
watch icon468

675
676
677
678
679
680
681
682
683
684
    t.error(err);

    var PNG = require('pngjs').PNG;
    var pixelmatch = require('pixelmatch');
    var expected = PNG.sync.read(
        fs.readFileSync(path.join(__dirname, '../fixtures/zoom-center/expected.png'))).data;
    var numPixels = pixelmatch(actual, expected, undefined, 400, 400, { threshold: 0.13 });
    t.equal(numPixels, 0);
    t.end();
});
fork icon170
star icon562
watch icon36

6
7
8
9
10
11
12
13
14
15
16
17
        `"{{ 'demo/$1' | relative_url }}"`);
    return "{% if page.is_react %}\n" + relativeSource + "\n{% endif %}\n";
}


function copyIndex(indexSrcPath, destFolderPath) {
    let indexSource = fs.readFileSync(indexSrcPath, 'utf8');
    let includesPath = path.join(destFolderPath, '../_includes');


    let match = indexSource.match(/<script defer="defer".*" rel="stylesheet">/);
    let modulesSource = `
fork icon54
star icon268
watch icon0

48
49
50
51
52
53
54
55
56
57
58
59
var http = require('http').Server(app);


if (config.UseHTTPS) {
	//HTTPS certificate details
	const options = {
		key: fs.readFileSync(path.join(__dirname, './certificates/client-key.pem')),
		cert: fs.readFileSync(path.join(__dirname, './certificates/client-cert.pem'))
	};


	var https = require('https').Server(options, app);
fork icon111
star icon197
watch icon17

+ 5 other calls in file

472
473
474
475
476
477
478
479
480
481
_parseGeoNamesCitiesCsv: function (pathToCsv, callback) {
  debug('Started parsing cities.txt (this  may take a while)');
  var data = [];
  var lenI = GEONAMES_COLUMNS.length;
  var that = this;
  var content = fs.readFileSync(pathToCsv);
  parse(content, { delimiter: '\t', quote: '' }, function (err, lines) {
    if (err) {
      return callback(err);
    }
fork icon51
star icon157
watch icon10

+ 25 other calls in file

132
133
134
135
136
137
138
139
140
141
  throw new Error(`${tr}:\n${util.inspect(proc)}`);
}

// Confirm that trace log file is created.
assert(fs.existsSync(traceFile));
const data = fs.readFileSync(traceFile);
const traces = JSON.parse(data.toString()).traceEvents;
assert(traces.length > 0);

// C++ fs sync trace events should be generated.
fork icon42
star icon19
watch icon0

495
496
497
498
499
500
501
502
503
504
505
506
  };


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


  assert.throws(
    () => fs.readFileSync(nonexistentFile),
    validateError
  );
}

fork icon42
star icon19
watch icon0

218
219
220
221
222
223
224
225
226
227
await (await getNREPL(args)).sendLine('1+2').waitClose()
await (await getNREPL(args)).sendLine('null').waitClose()
await (await getNREPL(args)).sendLine('"foobar"').waitClose()

// check history (as thoroughly as possible)
const historyFileContent = fs.readFileSync(historyPath, 'utf-8')
t.deepEqual(historyFileContent.split('\n'), ['1+2', 'null', '"foobar"', ''])

const n_ = await getNREPL()
n_.sendLine(`.load ${historyPath}`)
fork icon12
star icon122
watch icon4

+ 11 other calls in file

1
2
3
4
5
6
7
8
9
10
11
12
const { readFileSync, writeFileSync, readdirSync } = require('fs')
const { resolve, join } = require('path')
const dedent = require('dedent-js')


function alterFile(path) {
  let content = readFileSync(path, { encoding: 'utf-8' })


  content = content.replaceAll(
    `import DocsWrapper from 'src/docs/DocsWrapper'`,
    dedent(`
fork icon7
star icon40
watch icon0

54
55
56
57
58
59
60
61
62
63
  // like src="", url(""), a = "", srcset="xxx.jpg 100w, xxx@2.jpg 200w"
  return new RegExp(`${prefix}${content}`, 'g')
}

// read file
const read = (location) => readFileSync(location, 'utf-8')
// write file
const write = (location) => (content) => writeFileSync(location, content)
const readAsync = (location) =>
  new Promise((resolve, reject) => {
fork icon5
star icon18
watch icon3

+ 19 other calls in file