Nodejs 之 File System 模块

Nodejs 之 File System 模块

fs模块为nodejs的核心模块之一,主要处理文件的读写、复制、s删除、重命名等操作。当需要使用该模块时,需要先导入该文件

const fs = require('fs');

要注意的是 fs 是属于 nodejs 的内置模块所以不用特意的去 npm install 。

其次它的所有方法都有对应的异步和同步的模式;

All the methods have asynchronous and synchronous forms.

Here is an example of the asynchronous version:

const fs = require('fs');

fs.unlink('/tmp/hello', (err) => {
  if (err) throw err;
  console.log('successfully deleted /tmp/hello');
});

Here is the synchronous version:

const fs = require('fs');

fs.unlinkSync('/tmp/hello');
console.log('successfully deleted /tmp/hello');

一. fs 中的读写操作

文件模块中提供了基本的读写操作、buffer二进制操作和流操作。

wirte()和read()方法提供读写操作时,需要执行:

fs.open(path,flags,[mode],[callback(err,fd)])先打开文件。

fs.open(path, flags[, mode], callback)

flags can be: - #### ‘r’ - Open file for reading. An exception occurs if the file does not exist. - #### ‘r+’ - Open file for reading and writing. An exception occurs if the file does not exist.

- #### ‘rs+’ - Open file for reading and writing in synchronous mode. Instructs the operating system to bypass the local file system cache.

  • #### ‘w’ - Open file for writing. The file is created (if it does not exist) or truncated (if it exists).
  • ‘wx’ - Like ‘w’ but fails if path exists.

  • ‘w+’ - Open file for reading and writing. The file is created (if it does not exist) or truncated (if it exists).

  • ‘wx+’ - Like ‘w+’ but fails if path exists.

  • ‘a’ - Open file for appending. The file is created if it does not exist.

  • ‘ax’ - Like ‘a’ but fails if path exists.

  • ‘a+’ - Open file for reading and appending. The file is created if it does not exist.

  • ‘ax+’ - Like ‘a+’ but fails if path exists.


fs.read(fd, buffer, offset, length, position, callback)

其功能为从指定的文件描述符 fd 中读取数据并写入 buffer 指向的缓冲区对象。

offset 是buffer 的写入偏移量。

length 是要从文件中读取的字节数。

position 是文件读取的起始位置,如果 position 的值为 null,则会从当前文件指针的位置读取。

回调函数传递bytesRead 和 buffer,分别表示读取的字节数和缓冲区对象。

fs.write(fd, buffer[, offset[, length[, position]]], callback)

功能为将buffer内容写入fd中。

fs.readFile(path[, options], callback)

读取文件。其中file可以为文件名或文件路径,options可以为对象或字符串。包括读取文件时的编码、文件的读取方式(默认为‘r’);

fs.readFile('/etc/passwd', (err, data) => {
  if (err) throw err;
  console.log(data);
});

If options is a string, then it specifies the encoding. Example:

fs.readFile('/etc/passwd', 'utf8', callback);

注意:如果fd 是文件夹目录的形式则会报错!

// macOS, Linux and Windows
fs.readFile('<directory>', (err, data) => {
  // => [Error: EISDIR: illegal operation on a directory, read <directory>]
});

//  FreeBSD
fs.readFile('<directory>', (err, data) => {
  // => null, <data>
});

fs.writeFile(file, data[, options], callback)

Asynchronously writes data to a file, replacing the file if it already exists. data can be a string or a buffer.

The encoding option is ignored if data is a buffer. It defaults to ‘utf8’.

fs.writeFile('message.txt', 'Hello Node.js', (err) => {
  if (err) throw err;
  console.log('The file has been saved!');
}); 

If options is a string, then it specifies the encoding. Example:

fs.writeFile('message.txt', 'Hello Node.js', 'utf8', callback);
通过readFile和writeFile实现读取一个文件,并把该文件写入另一个文件中
fs.readFile('test.txt',(err,data) => {
    if(err){
        console.log(err)
    }
    fs.writeFile('test1.txt',data,0,'utf8',(err)  => {
        if(err){
            throw err;
        }
    })
})

二. fs 检查文件是否存在的方法

fs.stat(path, callback)

用于查询文件信息,其回调函数有两个参数(err, stats)。stats是一个fs.Stats对象,该对象中包含一个stats.isFile()方法。如果stats对象存在且stats.isFile()为true,才能确认要修改或删除的文件存在

fs.stat('test.txt',function(err,stat){
    if(stat && stat.isFile()){
        console.log("文件存在");
    }else{
        console.log('文件不存在或不是标准文件');
    }
})

fs.access(path[, mode], callback)

Tests a user’s permissions for the file or directory specified by path.

用于检查到指定path路径的目录或文件的访问权限,其回调函数中有一个参数(Err), 如果检查失败则会出现错误参数的响应。mode为要检查的权限掩码,它可以是以下的值

  • #### fs.constants.F_OK - path is visible to the calling process. This is useful for determining if a file exists, but says nothing about rwx permissions. Default if no mode is specified.文件是对于进程是否可见,可以用来检查文件是否存在。也是mode 的默认值
  • #### fs.constants.R_OK - path can be read by the calling process.
  • #### fs.constants.W_OK - path can be written by the calling process.
  • #### fs.constants.X_OK - path can be executed by the calling process. This has no effect on Windows (will behave like fs.constants.F_OK).文件对于进程是否可执行。(Windows系统不可用,执行效果等同fs.F_OK)
fs.access('/etc/passwd', fs.constants.R_OK | fs.constants.W_OK, (err) => {
  console.log(err ? 'no access!' : 'can read/write');
});

使用fs.acess()方法检查文件是否存在,可以使用以下方法

fs.access('test4.txt',function(err){
    console.log(err?'文件不存在':'文件存在');
})

使用fs.access方法检查对文件时候有读写权限,可以使用如下方法:

fs.access("test.txt",fs.R_OK | fs.W_OK,function(err){
    console.log(err?'不可读写':'可读写');
});

 fs.access(savePath, fs.W_OK, function (err) {
                    if (err) {
                        // todo
                    }
                    // 确认目录存在且有写权限,开始保存文件
                    fs.writeFile(filePath, file.buffer, function (err) {
                        if (err) {
                            logger.error(err);
                            reject('保存文件错误:' + err);
                        }
                        var URL = '/upload/' + fileName;
                        resolve(URL);
                    });
                });