SoFunction
Updated on 2025-03-03

Brief discussion: fs file system module

fs file system module, this is a very important module, and the operations on files are based on it. All methods of this module are synchronous and asynchronous. Let’s introduce the use of this module below.

1. Detect the permissions of the current process to the file

use(path[, mode], callback)Method check permissions, mode parameter is an integer with the following constant values:

  • .F_OK     path is visible to the calling process and exists
  • .R_OK     path is readable
  • .W_OK    path is writable
  • .X_OK     path is executable

Use as follows:

('./',.F_OK,(err)=>{
(err?'The file does not exist':'The file already exists');
});

Synchronous version, if an exception occurs, throw the exception directly, otherwise do nothing. The synchronous version can be done using try..catch, and all methods are applicable, as shown below:

try{
('./',.F_OK);
}catch(ex){
('The file does not exist');
}

2. Get file status

use(path, callback)(path)Method to obtain the traits of the specified path. Callback has two parameters (err, stats). stats is an object and has the following properties:

{ dev: 638212,
 mode: 33206,
 nlink: 1,
 uid: 0,
 gid: 0,
 rdev: 0,
 blksize: undefined,
 ino: 105553116266564850,
 size: 1094,
 blocks: undefined,
 atime: 2016-11-22T08:45:43.505Z,
 mtime: 2016-11-22T09:33:13.535Z,
 ctime: 2016-11-22T09:33:13.535Z,
 birthtime: 2016-11-22T08:45:43.505Z }

There are also the following methods:

()
 ()
 ()
 ()
 () (only valid with ())
 ()
 ()

Use as follows:

('./',(err,stats)=>{
  if(err) throw err;
  (stats);
});
var stats = ('../');//Synchronous version

3. File addition

use(file, data[, options], callback)Methods write data to file. If the file does not exist, create a file. The data parameter is a string or buffer. The optional parameters of options are objects or strings, with the following properties:

  • encoding  |  default = 'utf8' encoding
  • mode default = 0o666 Open mode
  • flag  default = 'a'

Use as follows:

('./','hello world!\r\n',(err)=>{
  if(err) throw err;
  ('Writing successfully');
});
//The synchronous version of appendFile, the return value is undefined('./','hello nodejs!\r\n');

4. File reading and writing

File reading usage(file[, options], callback)Method, parameter meaning is as follows:

  • file file name or file descriptor
  • options object or string, if it is an object, it contains encoding and flag. The former defaults to null and the latter is 'r'
  • The callback parameter is (err,data)

If the specified file does not exist, an error will be directly thrown. Use as follows:

('./',{encoding:'utf8',flag:'r'},(err,data)=>{
if(err) throw err;
(data);
});
var data = ('../',{encoding:'utf8',flag:'r'});

Write data to file, use(file, data[, options], callback)Method, parameter meaning is as follows:

  • file file name or file descriptor
  • data string or buffer
  • options object or string, if it is an object, it contains encoding, mode and flag, and defaults to utf8, 0o666, 'w'
  • callback parameter err

If the specified file does not exist, create the file, and instead replace the original file. Use as follows:

var data = "hello node!";
('./',data,{flag:'w'},(err)=>{
if(err) throw err;
('written ok.');
});
('./',data,{flag:'w'});

We can also use open, read, write, stat and other methods of fs to realize the reading and writing of files.

(path, flags[, mode], callback)Methods open a file to get the handle, and the flags parameters have the following:

  • 'r' - Open the file in read-only mode, and if the file does not exist, an error will be reported.
  • 'r+' - Open the file in a read-write manner, and if the file does not exist, an error will be reported.
  • 'rs+' Open the file in synchronous mode in read and write mode
  • 'w' - Open the file in writing, create it if the file does not exist.
  • 'wx' - Open the file in a write mode, throw an exception if the file does not exist.
  • 'w+' - Open the file in a read-write manner. If the file does not exist, create it, and instead clear the file.
  • 'wx+' - Open the file in a read-write manner, and throw an exception if the file does not exist.
  • 'a' - Open the file in append mode, and create the file if the file does not exist.
  • 'ax' - Open the file in append mode, throw an exception if the file does not exist.
  • 'a+' - Open the file in append and read mode, and create the file if the file does not exist.
  • 'ax+' - Open the file in append and read mode, if the file does not exist, it will fail

The callback callback function has two parameters (err,fd).

(fd, buffer, offset, length, position, callback)Method: read data from a file and store it into a buffer. The parameters are as follows:

  • Buffer Buffer object, used to store read data
  • where the offset buffer starts writing
  • length The length that needs to be read
  • position Specifies where to start reading in the file. If set to null, it starts reading from the current location of the file.
  • callback has three parameters (err, bytesRead, buffer) bytesRead is the actual number of bytes read
  • (fd, buffer, offset, length[, position], callback)Method: Write buffer data as specified in the file, the parameters are as follows:
  • offset and length specify the buffer part of the buffer
  • position Specifies the file to start writing to the file. If it is not a number, it starts writing from the current location of the file.

The following is a function to copy file contents using the open, write, read, and stat methods, as shown below:

function copy(src, dest) {
const destFd = (dest, 'w+'),
   srcStat = (src);
const buffer = new Buffer();
('Copy starts...');
(src+'size:'+)
(src,'r',(err,fd)=>{
  if(err) throw err;
  (fd,buffer,0,,null,(err,bytesRead,buff)=>{
    if(err) throw err;
    ('Actual read size:'+bytesRead);
    (fd,()=>{});
    (destFd,buff,0,bytesRead,null,(err, written, buffer)=>{
      if(err) throw err;
      ('Copy completed, to'+dest+'Written'+written);
      (destFd,()=>{});
    });
  });
});
}
copy('./','./');

The execution results are as follows:

E:\developmentdocument\nodejsdemo>node
Copying begins...
./Size: 1094
Actual read size: 1094
Copying has been completed, 1094 was written to ./

5. Rename and delete file

method(oldPath, newPath, callback)You can realize file renaming and file movement. If oldPath and newPath are in the same directory, it is renaming. Otherwise, it is moving the file and renaming it, using the following:

('../','./',(err)=>{
  if(err) throw err;
  ('rename success.');
});
('../','../');

File deletion is required(path, callback)The method is also very simple to use, as shown below:

('./dir/',(err)=>{
  if(err) throw err;
  ('delete file success.');
});
('./dir/');

6. Create, read, delete directories

The directory is created using(path[, mode], callback)Method, mode parameter defaults to 0o777, but this method can only create a first-level directory, otherwise an exception will be thrown, as shown below:

('./a',0o777,(err)=>{
  if(err) throw err;
  ('mkdir success');
});
//The synchronous version of mkdir, the return value is undefined('./test',0o777);

In order to be able to create multi-level directories, you can define a function to implement it yourself. You need to use the dirname method of the path module, as shown below:

function isFileExists(filePath){
  var bool = !0;
  try{
    (filePath,fs.F_OK);
  }catch(err){
    bool = !1;
  }
  return bool;
}
function mkdirp(dirpath,mode,cb){
  if(isFileExists(dirpath)){
    cb(dirpath);
  }else{
    mkdirp((dirpath),mode,function(){
      (dirpath,mode,cb);
    });
  }
}

Scan the directory to use(path[, options], callback)The method, the options parameter is a string or object, the callback callback function has two parameters (err, files). files is an array of file names. This method can only scan first-level directories, and uses it as follows:

('./',(err,files)=>{
  if(err) throw err;
  (files);
});

If you want to implement the ability to scan the directory recursively, you can define a function yourself, as shown below:

function scandir(dirpath){
  var filesArr = {};
  if(!isFileExists(dirpath)) return !1;
  function scan(filepath){
    var statObj = (filepath);
    if(!()) return (filepath);
    var files = (filepath);
    ((file,idx,arr)=>{
      scan(filepath+'/'+file);
    });
  }
  scan(dirpath);
  return filesArr;
}

Delete directory use(path, callback)Methods: Only first-level directories can be deleted and the directories must be empty, and use them as follows:

('./dir',(err)=>{
  if(err) throw err;
  ('delete dir success.');
});

To achieve a recursive deletion effect similar to rm -rf, you can use the following code:

function deldirs(dirpath){
  var stat = null,
    emptyFoldersArr = [];
  
  function scan(spath){
    var files = (spath);
    (spath);
    if(>0){
      ((file,idx,arr)=>{
        if((spath+'/'+file).isDirectory()){
          scan(spath+'/'+file);
        }else{
          return (spath+'/'+file),!0;
        }
      });
    }
  }
  scan(dirpath);
  for(var l=-1,i=l;i>=0;i--){
    (emptyFoldersArr[i]);
  }
}

7. Get the absolute path of the path

use(path[, options], callback)The method can obtain the absolute path of path. Callback has two parameters (err, resolvedPath), which is as follows:

('./',(err,resolvePath)=>{
  if(err) throw err;
  (resolvePath);
});
(('./'));

The execution results are as follows:

E:\developmentdocument\nodejsdemo>node
E:\developmentdocument\nodejsdemo\

The above is all the content of this article. I hope it will be helpful to everyone's study and I hope everyone will support me more.