Discussion on Node.js:fs file system module _node.js

Source: Internet
Author: User
Tags create directory mkdir readfile file permissions

FS File system module, this is a very important module, the operation of the file is based on it. All of the methods of the module are synchronous and asynchronous, and the use of the module is described below.

1, detect the current process of the file permissions

Use fs.access(path[, mode], callback) method to check permissions, the Mode argument is an integer with the following constant values:

    • Fs.constants.F_OK path is visible to the calling process, both
    • Fs.constants.R_OK path is readable
    • Fs.constants.W_OK path is writable.
    • Fs.constants.X_OK path is executable.

Use the following example:

Fs.access ('./note.txt ', Fs.constants.F_OK, (err) =>{
console.log (err?) File does not exist ': ' File already exists ';
};

Sync version, if an exception occurs, throw an exception directly, otherwise do nothing. Synchronized versions can take advantage of try ... Catch to do all of the methods, as follows:

try{
Fs.accesssync ('./note.txt ', Fs.constants.F_OK);
} catch (ex) {
console.log (' File not present ');
}

2. Get File status

Use fs.stat(path, callback) , fs.statSync(path) method to get the shape of the specified path, callback has (err, stats) Two parameters, stats is Fs.stats object with 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:

Stats.isfile ()
 stats.isdirectory ()
 stats.isblockdevice ()
 stats.ischaracterdevice
 () Stats.issymboliclink () (only valid with Fs.lstat ())
 Stats.isfifo ()
 stats.issocket ()

Use the following example:

Fs.stat ('./app.js ', (err,stats) =>{
  if (err) throw err;
  Console.log (stats);
});
var stats = Fs.statsync ('.. /test.txt ');/sync version

3, File append

Use the fs.appendFile(file, data[, options], callback) method to write data to file, and if file does not exist, create the File,data parameter as a string or buffer,options optional parameter is an object or string with the following properties:

    • encoding | default = ' UTF8 ' encoding
    • Mode default = 0o666 open mode
    • Flag default = ' A '

Use the following example:

Fs.appendfile ('./test.txt ', ' Hello world!\r\n ', (err) =>{
  if (err) throw err;
  Console.log (' write Success ');
};
AppendFile synchronous version, the return value is undefined
fs.appendfilesync ('./test.txt ', ' Hello nodejs!\r\n ');

4, file read and write

File read using fs.readFile(file[, options], callback) method, parameter meaning is as follows:

    • File file name or filename descriptor
    • The options object or string, if it is an object, contains encoding and flag, the former defaults to null, and the latter is ' R '
    • Callback parameter is (Err,data)

If the specified file does not exist, the error is thrown directly. Use the following example:

Fs.readfile ('./test4.txt ', {encoding: ' UTF8 ', flag: ' R '}, (Err,data) =>{
if (err) throw err;
Console.log (data);
var data = Fs.readfilesync ('.. /test4.txt ', {encoding: ' UTF8 ', flag: ' R '});

The file writes the data, uses fs.writeFile(file, data[, options], callback) the method, the parameter meaning is as follows:

    • File file name or filename descriptor
    • Data string or buffer
    • The options object or string, if it is an object, contains encoding, mode, and flag, which, in turn, defaults to utf8,0o666, ' W '
    • Callback Parameter Err

If the specified file does not exist, the file is created, and instead the original file is replaced. Use the following example:

var data = "Hello node!";
Fs.writefile ('./test1.txt ', Data,{flag: ' W '}, (err) =>{
if (err) throw err;
Console.log (' written ok. ');
Fs.writefilesync ('./test1.txt ', Data,{flag: ' W '});

We can also use the Open,read,write,stat of FS to realize the reading and writing of files.

fs.open(path, flags[, mode], callback)Method opens a file fetch handle, which has the following flags parameter:

    • ' R '-opens the file as read-only and complains if the file does not exist.
    • ' r+ '-open the file in read-write mode, if the file does not exist, the error.
    • ' rs+ ' in sync mode, open files in read-write mode
    • ' W '-open the file as write and create if the file does not exist
    • ' WX '-opens the file as a write and throws an exception if the file does not exist.
    • ' w+ '-opens the file as read-write, creates the file if it does not exist, and empties the file instead.
    • ' wx+ '-opens the file in read-write mode and throws an exception if the file does not exist.
    • ' A '-open the file as an append, and create a file if the file is not saved
    • ' Ax '-opens the file as an append, and throws an exception if the file is not saved.
    • ' A + '-opens the file by appending and reading, creating the file if the file is not saved
    • ' ax+ '-Opens the file in append and read mode and fails if the file is not saved

The callback callback function has (ERR,FD) two parameters.

fs.read(fd, buffer, offset, length, position, callback)method, read data from a file into the buffer, the parameter meaning is as follows:

    • A buffer buffer object that is used to store read data
    • Offset buffer where to start writing
    • Length to read
    • Position specifies where to start reading from the file and, if set to NULL, start reading from the current location of the file
    • Callback has three parameters (err, bytesread, buffer) Bytesread The actual number of bytes read
    • fs.write(fd, buffer, offset, length[, position], callback)method, the buffer data is written as the specified file, and the parameter meanings are as follows:
    • Offset and length Specify the portion of the buffer
    • Position the file at which the specified file is to be written, and if not a number, writes from the current location of the file

The following is a function of copying the contents of a file using the Open,write,read,stat method, as follows:

function copy (src, dest) {
Const DESTFD = Fs.opensync (dest, ' w+ '),
   srcstat = Fs.statsync (src);
Const BUFFER = new buffer (srcstat.size);
Console.log (' Copy begins ... ');
Console.log (src+ ' size: ' +srcstat.size ')
fs.open (src, ' r ', (ERR,FD) =>{
  if (err) throw err;
  Fs.read (Fd,buffer,0,srcstat.size,null, (err,bytesread,buff) =>{
    if (err) throw err;
    Console.log (' actual read size: ' +bytesread ');
    Fs.close (FD, () =>{});
    Fs.write (Destfd,buff,0,bytesread,null, (err, written, buffer) =>{
      if (err) throw err;
      Console.log (' Completed replication, to ' +dest+ ' written to ' +written ');
      Fs.close (DESTFD, () =>{})
;});};} Copy ('./app.js ', './appbak.js ');

The results of the implementation are as follows:

E:\developmentdocument\nodejsdemo>node Fs-examples.js
Copy start ...
./app.js Size: 1094
Actual Read size: 1094
Copy completed, write to./appbak.js 1094

5, file Rename, delete

Methods fs.rename(oldPath, newPath, callback) can be renamed file, but also to achieve the movement of files, if OldPath and NewPath in the same directory, it is renamed, or move the file and rename, using the following:

Fs.rename ('.. /test4.txt ', './test4.txt ', (err) =>{
  if (err) throw err;
  Console.log (' rename success. ');
Fs.renamesync ('.. /test2.txt ', '. /test4.txt ');

File deletion requires a fs.unlink(path, callback) method and is simple to use, as follows:

Fs.unlink ('./dir/11.txt ', (err) =>{
  if (err) throw err;
  Console.log (' Delete file success. ');
});
Fs.unlinksync ('./dir/11.txt ');

6, create, read, delete directory

The Create directory uses a fs.mkdir(path[, mode], callback) method, the mode parameter defaults to 0o777, but the method can only create a level of directory, otherwise throw an exception as follows:

Fs.mkdir ('. A ', 0o777, (err) =>{
  if (err) throw err;
  Console.log (' mkdir success ');
};
mkdir synchronization version, the return value is undefined
fs.mkdirsync ('./test ', 0o777);

In order to be able to create a multi-level directory, you can define a function to implement it, and you need to use the DirName method of the path module, as follows:

function Isfileexists (filePath) {
  var bool =! 0;
  try{
    Fs.accesssync (filepath,fs. F_OK);
  } catch (Err) {
    bool =! 1;
  }
  return bool;
}
function Mkdirp (DIRPATH,MODE,CB) {
  if (isfileexists (Dirpath)) {
    CB (Dirpath);
  } else{
    mkdirp (Path.dirname (Dirpath), mode,function () {
      fs.mkdir (DIRPATH,MODE,CB);
    });
  }


Scan directory requires a fs.readdir(path[, options], callback) method, the options parameter is a string or object, the callback callback function has (err, files) two parameters, files is an array of file names, the method can only scan the first level of directories, using the following:

Fs.readdir ('./', (err,files) =>{
  if (err) throw err;
  Console.log (files);

If you want to implement a recursive scan of a directory, you can define a function yourself, as follows:

function Scandir (dirpath) {
  var filesarr = {};
  if (!isfileexists (Dirpath)) return! 1;
  function Scan (filepath) {
    var statobj = Fs.statsync (filepath);
    if (!statobj.isdirectory ()) return Filesarr.push (filepath);
    var files = fs.readdirsync (filepath);
    Files.foreach ((File,idx,arr) =>{
      Scan (filepath+ '/' +file);}
    );
  }
  Scan (dirpath);
  return filesarr;
}

Deletes the directory usage fs.rmdir(path, callback) method, only deletes the level directory and the directory must be empty, uses as follows:

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

To implement a recursive delete effect similar to RM-RF, you can use the following code:

function Deldirs (dirpath) {
  var stat = null,
    Emptyfoldersarr = [];
  
  function Scan (spath) {
    var files = fs.readdirsync (spath);
    Emptyfoldersarr.push (spath);
    if (files.length>0) {
      Files.foreach (File,idx,arr) =>{if (Fs.statsync (spath+
        '/' +file). Isdirectory () ) {
          scan (spath+ '/' +file);
        } else{return
          fs.unlinksync (spath+ '/' +file),! 0
        }}
      );
    }
  Scan (dirpath);
  for (Var l=emptyfoldersarr.length-1,i=l;i>=0;i--) {
    fs.rmdirsync (emptyfoldersarr[i]);
  }

7, get the absolute path of the path

Use the fs.realpath(path[, options], callback) method to get the absolute path of path, callback (err, Resolvedpath) two parameters, using the following:

Fs.realpath ('./test.txt ', (err,resolvepath) =>{
  if (err) throw err;
  Console.log (Resolvepath);
});
Console.log (Fs.realpathsync ('./test.txt '));

The results of the execution are as follows:

E:\developmentdocument\nodejsdemo>node Fs-examples.js
E:\developmentdocument\nodejsdemo\test.txt

The above is the entire content of this article, I hope to help you learn, but also hope that we support the cloud habitat community.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.