📜  Node.js fs.open() 方法

📅  最后修改于: 2022-05-13 01:56:41.165000             🧑  作者: Mango

Node.js fs.open() 方法

简介:使用fs.open() 方法创建文件、写入文件或读取文件。 fs.readFile()仅用于读取文件,类似地fs.writeFile()仅用于写入文件,而fs.open() 方法对文件执行多项操作。首先我们需要加载fs类,它是访问物理文件系统的模块。因为它需要使用方法。例如: var fs = require('fs');
句法:

fs.open( filename, flags, mode, callback )

参数:此方法接受上面提到的四个参数,如下所述:

  • 文件名:它保存要读取的文件的名称或存储在其他位置的整个路径。
  • flag:必须打开文件的操作。
  • mode:设置文件的模式,即r-read、w-write、r+-readwrite。它设置为默认为读写。
  • callback:读取文件后调用的回调函数。它需要两个参数:
    • err:如果发生任何错误。
    • data:一个文件描述符,供后续文件操作使用。文件描述符是用于访问文件的句柄。它是唯一引用特定文件的非负整数。

所有类型的标志描述如下:

FlagDescription
rTo open file to read and throws exception if file doesn’t exists.
r+Open file to read and write. Throws exception if file doesn’t exists.
rs+Open file in synchronous mode to read and write.
wOpen file for writing. File is created if it doesn’t exists.
wxIt is same as ‘w’ but fails if path exists.
w+Open file to read and write. File is created if it doesn’t exists.
wx+It is same as ‘w+’ but fails if path exists.
aOpen file to append. File is created if it doesn’t exists.
axIt is same as ‘a’ but fails if path exists.
a+Open file for reading and appending. File is created if it doesn’t exists.
ax+It is same as ‘a+’ but fails if path exists.

下面的示例说明了 Node.js 中的 fs.open() 方法:
示例 1:

javascript
// Node.js program to demonstrate the   
// fs.open() Method
  
// Include the fs module
var fs = require('fs');
 
// Open file demo.txt in read mode
fs.open('demo.txt', 'r', function (err, f) {
  console.log('Saved!');
});


javascript
// Node.js program to demonstrate the   
// fs.open() Method
  
// Include the fs module
var fs = require('fs');
 
console.log("Open file!");
 
// To open file in write and read mode,
// create file if doesn't exists.
fs.open('demo.txt', 'w+', function (err, f) {
   if (err) {
      return console.error(err);
   }
   console.log(f);
   console.log("File opened!!");    
});


输出:

Saved! 

解释:
文件被打开并且标志被设置为读取模式。打开文件后调用函数读取文件内容并存储在内存中。由于没有错误,因此打印了“已保存”。
示例 2:

javascript

// Node.js program to demonstrate the   
// fs.open() Method
  
// Include the fs module
var fs = require('fs');
 
console.log("Open file!");
 
// To open file in write and read mode,
// create file if doesn't exists.
fs.open('demo.txt', 'w+', function (err, f) {
   if (err) {
      return console.error(err);
   }
   console.log(f);
   console.log("File opened!!");    
});

输出:

Open file!
10
File Opened!

说明:以读写方式打开文件'demo.txt',然后调用该函数。当我们打印“f”的值时,输出会在文件中显示一个数字。
参考: https://nodejs.org/api/fs.html#fs_fs_open_path_flags_mode_callback