How to use the open function from fs-extra

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

fs-extra.open is a function in the fs-extra library, a drop-in replacement for the Node.js fs module, that opens a file for reading or writing, or creates the file if it does not exist, with some additional options.

248
249
250
251
252
253
254
255
256
257
root.file("clusterio.json", JSON.stringify(patchInfo, null, 4));

// Write back the save
let tempSavePath = `${savePath}.tmp`;
let stream = zip.generateNodeStream({ compression: "DEFLATE" });
let fd = await fs.open(tempSavePath, "w");
try {
	let pipe = stream.pipe(fs.createWriteStream("", { fd, autoClose: false }));
	await events.once(pipe, "finish");
	await fs.fsync(fd);
fork icon58
star icon228
watch icon0

138
139
140
141
142
143
144
145
146
147
let directory = path.dirname(file);
if (!await fs.pathExists(directory)) {
	await fs.mkdirs(directory);
}
let temporary = `${file}.tmp`;
let fd = await fs.open(temporary, "w");
try {
	await fs.writeFile(fd, data, options);
	await fs.fsync(fd);
} finally {
fork icon58
star icon228
watch icon0

How does fs-extra.open work?

fs-extra.open is a function in the fs-extra library, a drop-in replacement for the Node.js fs module, that opens a file for reading or writing, or creates the file if it does not exist, with some additional options.

When called, fs-extra.open takes three required arguments: the path of the file to open or create, a string indicating the file mode to use, and an optional options object that can specify additional options, such as the file encoding or file permissions.

For example, to open a file for reading with UTF-8 encoding, we could call fs-extra.open like this:

javascript
const fs = require('fs-extra'); fs.open('myfile.txt', 'r', { encoding: 'utf8' }, (err, fd) => { if (err) throw err; // do something with the file descriptor (fd) });

In this example, we use fs-extra.open to open the file 'myfile.txt' for reading with UTF-8 encoding. The second argument 'r' specifies that the file should be opened in read-only mode.

The third argument is an options object that specifies the 'utf8' encoding to use for the file. This object could also include other options, such as the file mode or file permissions.

When fs-extra.open is called with the file path, mode, and options, it returns a file descriptor (fd) that can be used to read from or write to the file. We pass a callback function that will be called with an error if one occurred, or the file descriptor if the file was opened successfully.

Similarly, we can use fs-extra.open to create a new file for writing with specific file permissions:

javascript
fs.open('newfile.txt', 'w', { mode: 0o644 }, (err, fd) => { if (err) throw err; // do something with the file descriptor (fd) });

In this example, we use fs-extra.open to create a new file 'newfile.txt' for writing. The second argument 'w' specifies that the file should be opened in write-only mode, creating a new file if it does not exist or overwriting the existing file if it does.

The third argument is an options object that specifies the file permissions to use for the file, in octal format. In this case, we use the value 0o644, which specifies that the owner can read and write the file, and all others can only read the file.

The fs-extra.open function is useful for working with files in Node.js, allowing us to read and write files in a variety of modes and with additional options.

718
719
720
721
722
723
724
725
726
727
patch.status = 'loaded'
if (file) {
  patch.file = patch.originalFile
  const filePath = datasetUtils.filePath({ ...dataset, ...patch })
  // Try to prevent weird bug with NFS by forcing syncing file before sampling
  const fd = await fs.open(filePath, 'r')
  await fs.fsync(fd)
  await fs.close(fd)
  const fileSample = await datasetFileSample({ ...dataset, ...patch })
  debugFiles(`Attempt to detect encoding from ${fileSample.length} first bytes of file ${filePath}`)
fork icon6
star icon26
watch icon4

232
233
234
235
236
237
238
239
240
241
- fs.createReadStream():创建可读的文件流
- fs.createWriteStream():创建可写文件流
- fs.link():创建指向文件的新硬链接
- fs.mkdir(): 新建一个文件夹
- fs.mkdtemp():创建一个临时目录
- fs.open():设置文件模式
- fs.readdir():读取目录的内容
- fs.readFile():读取文件的内容。有关:fs.read()
- fs.readlink():读取符号链接的值
- fs.realpath():将相对文件路径指针(.,..)解析为完整路径
fork icon0
star icon12
watch icon1

+ 13 other calls in file

Ai Example

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
const fs = require("fs-extra");

fs.open("myfile.txt", "r", { encoding: "utf8" }, (err, fd) => {
  if (err) {
    console.error(err);
    return;
  }

  // Read from the file using the file descriptor
  const buffer = Buffer.alloc(1024);
  fs.read(fd, buffer, 0, buffer.length, null, (err, bytesRead, buffer) => {
    if (err) throw err;

    console.log(`Read ${bytesRead} bytes: ${buffer.toString()}`);

    // Close the file descriptor when we're done
    fs.close(fd, (err) => {
      if (err) throw err;
      console.log("File closed successfully");
    });
  });
});

In this example, we use fs-extra.open to open the file 'myfile.txt' for reading with UTF-8 encoding. The second argument 'r' specifies that the file should be opened in read-only mode. When fs-extra.open is called with the file path, mode, and options, it returns a file descriptor (fd) that can be used to read from or write to the file. We pass a callback function that will be called with an error if one occurred, or the file descriptor if the file was opened successfully. We then read from the file using fs.read, passing the file descriptor, a buffer to read the data into, and a callback function that will be called with the number of bytes read and the buffer of data. When we're done reading, we close the file descriptor using fs.close, passing the file descriptor and a callback function that will be called when the file is closed. This is just one example of how fs-extra.open can be used in Node.js to work with files. We could also use it to open a file for writing or both reading and writing, depending on our needs. We can also use the optional options argument to specify additional options, such as file permissions or flags.

76
77
78
79
80
81
82
83
84
85
}

watch(child, parent) {
  fs.watchFile(child, { interval: 300 }, (curr, prev) => {
    if (curr.mtime > prev.mtime) {
      fs.open(parent, 0, function(err, fd) {
        if (err) return console.log(err)

        fs.fstat(fd, function(err) {
          if (err) return console.log(err)
fork icon1
star icon4
watch icon0

1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
});

judge_result = JSON.parse(judge_result.replace(/\n/g,"\\\\n"))
if(await fs.exists(output_path)) {
  judge_result.output =  await new Promise((resolve, reject) => {
    fs.open(output_path, 'r', function(status, fd) {
      if(status) {
        resolve(null)
        return
      }
fork icon1
star icon1
watch icon1

+ 6 other calls in file

8916
8917
8918
8919
8920
8921
8922
8923
8924
8925

// 550 millis past UNIX epoch
const d = new Date(1435410243862)
fs.writeFile(tmpfile, 'https://github.com/jprichardson/node-fs-extra/pull/141', err => {
  if (err) return callback(err)
  fs.open(tmpfile, 'r+', (err, fd) => {
    if (err) return callback(err)
    fs.futimes(fd, d, d, err => {
      if (err) return callback(err)
      fs.close(fd, err => {
fork icon0
star icon1
watch icon0

+ 62 other calls in file

5
6
7
8
9
10
11
12
13
14
const withStreamableFile = async (filePath, fn) => {
  // creating empty file before streaming seems to fix some weird bugs with NFS
  await fs.ensureFile(filePath + '.tmp')
  await fn(fs.createWriteStream(filePath + '.tmp'))
  // Try to prevent weird bug with NFS by forcing syncing file before reading it
  const fd = await fs.open(filePath + '.tmp', 'r')
  await fs.fsync(fd)
  await fs.close(fd)
  // write in tmp file then move it for a safer operation that doesn't create partial files
  await fs.move(filePath + '.tmp', filePath, { overwrite: true })
fork icon0
star icon0
watch icon0

73
74
75
76
77
78
79
80
81
} else {
  throw new Error(`protocole non supporté "${url.protocol}"`)
}

// Try to prevent weird bug with NFS by forcing syncing file before reading it
const fd = await fs.open(tmpFile, 'r')
await fs.fsync(fd)
await fs.close(fd)
await log.info(`le fichier a été téléchargé (${filename})`)
fork icon0
star icon0
watch icon0

25
26
27
28
29
30
31
32
33
    }
    throw err
  }

  // Try to prevent weird bug with NFS by forcing syncing file before reading it
  const fd = await fs.open(file, 'r')
  await fs.fsync(fd)
  await fs.close(fd)
}
fork icon0
star icon0
watch icon0

322
323
324
325
326
327
328
329
330
331
    open: callback => {
        if (!isWriter) {
            return callback();
        }

        Fs.open(clientContext.server.path(location), data.type === OPEN_MODE.WRITE ? 'w' : 'a', 0o644, callback);
    },
}, (error, results) => {
    if (error) {
        clientContext.server.log.warn({
fork icon0
star icon0
watch icon0

+ 4 other calls in file

function icon

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