Node.js file system

Posted by jay1318 on Sat, 05 Mar 2022 16:10:31 +0100

1, Node JS file system

Node.js provides a set of file manipulation API s similar to the UNIX (POSIX) standard. Node import file system module (fs) syntax is as follows:

2, Asynchronous and synchronous

Node. The methods in the JS file system (fs module) module have asynchronous and synchronous versions. For example, the functions that read the contents of the file have asynchronous fs Readfile() and synchronized fs readFileSync().
The last parameter of the asynchronous method function is the callback function, and the first parameter of the callback function contains error information.
Asynchronous method is recommended. Compared with synchronous method, asynchronous method has higher performance, faster speed and no blocking.

// example
var fs = require("fs");

// Asynchronous read
fs.readFile('input.txt', function (err, data) {
   if (err) {
       return console.error(err);
   }
   console.log("Asynchronous read: " + data.toString());
});

// Synchronous reading
var data = fs.readFileSync('input.txt');
console.log("Synchronous reading: " + data.toString());

console.log("Program execution completed.");

3, Open file

(1) Syntax format for opening files in asynchronous mode:

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

(2) The parameters are described as follows:

  • Path - the path to the file.
  • flags - the behavior of opening a file. See the following for specific values.
  • Mode - set the file mode (permission). The default permission for file creation is 0666 (readable and writable).
  • Callback - callback function with two parameters, such as callback(err, fd).

The flags parameter can be the following values:

Flagdescribe
rOpen the file in read mode. Throw an exception if the file does not exist.
r+Open the file in read-write mode. Throw an exception if the file does not exist.
rsRead files synchronously.
rs+Read and write files synchronously.
wOpen the file in write mode and create it if it does not exist.
wxSimilar to 'w', but if the file path exists, the file write fails.
w+Open the file in read-write mode and create it if it does not exist.
wx+Similar to 'w +', but if the file path exists, the file reading and writing fails.
aOpen the file in append mode and create it if it does not exist.
axSimilar to 'a', but if the file path exists, the file append fails.
a+Open the file in read append mode and create it if it does not exist.
ax+Similar to 'a +', but if the file path exists, the file read append fails.
// example
// Create file JS file and open input Txt file. The code is as follows:
var fs = require("fs");

// Open file asynchronously
console.log("Ready to open the file!");
fs.open('input.txt', 'r+', function(err, fd) {
   if (err) {
       return console.error(err);
   }
  console.log("File opened successfully!");     
});

// The execution results of the above code are as follows
 Ready to open the file!
File opened successfully!

4, Get file information

(1) Syntax format of obtaining file information through asynchronous mode:

  • fs.stat(path, callback)

(2) The parameters are described as follows:

  • Path - file path.
  • Callback - callback function with two parameters, for example: (err, stats), stats is FS Stats object.

fs. After the stat class executes its callback (path), it will be returned to the stat class. You can judge the relevant attributes of the file through the methods provided in the stats class. For example, judge whether it is a file:

var fs = require('fs');

fs.stat('/Users/liuht/code/itbilu/demo/fs.js', function (err, stats) {
    console.log(stats.isFile());         //true
})

The methods in stats class are:

methoddescribe
stats.isFile()If it is a file, return true; otherwise, return false.
stats.isDirectory()If it is a directory, return true; otherwise, return false.
stats.isBlockDevice()If it is a block device, return true; otherwise, return false.
stats.isCharacterDevice()If it is a character, the device returns true; otherwise, it returns false.
stats.isSymbolicLink()If it is a soft link, return true; otherwise, return false.
stats.isFIFO()If it is FIFO, return true; otherwise, return false. FIFO is a special type of command pipeline in UNIX.
stats.isSocket()If it is Socket, return true; otherwise, return false.
// Instance: create file JS file, the code is as follows:
var fs = require("fs");

console.log("Ready to open the file!");
fs.stat('input.txt', function (err, stats) {
   if (err) {
       return console.error(err);
   }
   console.log(stats);
   console.log("Read file information successfully!");
   
   // Detection file type
   console.log("Is it a file(isFile) ? " + stats.isFile());
   console.log("Is it a directory(isDirectory) ? " + stats.isDirectory());    
});

// The execution results of the above code are as follows:
Ready to open the file!
{ dev: 16777220,
  mode: 33188,
  nlink: 1,
  uid: 501,
  gid: 20,
  rdev: 0,
  blksize: 4096,
  ino: 40333161,
  size: 61,
  blocks: 8,
  atime: Mon Sep 07 2015 17:43:55 GMT+0800 (CST),
  mtime: Mon Sep 07 2015 17:22:35 GMT+0800 (CST),
  ctime: Mon Sep 07 2015 17:22:35 GMT+0800 (CST) }
Read file information successfully!
Is it a file(isFile) ? true
 Is it a directory(isDirectory) ? false

5, Write file

(1) Syntax format for writing files in asynchronous mode:

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

writeFile directly opens the file in w mode by default, so if the file exists, the contents written by this method will overwrite the contents of the old file.
(2) The parameters are described as follows:

  • File - file name or file descriptor.
  • Data - the data to be written to the file, which can be a string or buffer object.
  • options - this parameter is an object containing {encoding, mode, flag}. The default code is utf8, the mode is 0666, and the flag is' w '
  • Callback - callback function. The callback function only contains the error information parameter (err), which is returned when writing fails.
// Instance: create file JS file, the code is as follows:
var fs = require("fs");

console.log("Ready to write to file");
fs.writeFile('input.txt', 'I passed fs.writeFile Write the contents of the file',  function(err) {
   if (err) {
       return console.error(err);
   }
   console.log("Data writing succeeded!");
   console.log("--------I am the dividing line-------------")
   console.log("Read and write data!");
   fs.readFile('input.txt', function (err, data) {
      if (err) {
         return console.error(err);
      }
      console.log("Read file data asynchronously: " + data.toString());
   });
});

// The execution results of the above code are as follows:
Ready to write to file
 Data writing succeeded!
--------I am the dividing line-------------
Read and write data!
Read file data asynchronously: I passed fs.writeFile Write the contents of the file

6, Read file

(1) Syntax format of reading files in asynchronous mode:

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

This method uses the file descriptor to read the file.
(2) The parameters are described as follows:

  • fd - through FS The file descriptor returned by the open () method.
  • Buffer - buffer for data writing.
  • Offset - the write offset of the buffer write.
  • length - the number of bytes to read from the file.
  • Position - the starting position of the file reading. If the value of position is null, it will be read from the position of the current file pointer.
  • Callback - callback function, which has three parameters: err, bytesRead and buffer. Err is the error information, bytesRead represents the number of bytes read, and buffer is the buffer object.
// example
var fs = require("fs");
var buf = new Buffer.alloc(1024);

console.log("Ready to open the existing file!");
fs.open('input.txt', 'r+', function(err, fd) {
   if (err) {
       return console.error(err);
   }
   console.log("File opened successfully!");
   console.log("Ready to read file:");
   fs.read(fd, buf, 0, buf.length, 0, function(err, bytes){
      if (err){
         console.log(err);
      }
      console.log(bytes + "  Byte read");
      
      // Output only read bytes
      if(bytes > 0){
         console.log(buf.slice(0, bytes).toString());
      }
   });
});

7, Close file

(1) Syntax format of closing file in asynchronous mode:

  • fs.close(fd, callback)

This method uses the file descriptor to read the file.

(2) The parameters are described as follows:

  • fd - through FS The file descriptor returned by the open () method.
  • Callback - callback function, no parameters.
// example
var fs = require("fs");
var buf = new Buffer.alloc(1024);

console.log("Ready to open the file!");
fs.open('input.txt', 'r+', function(err, fd) {
   if (err) {
       return console.error(err);
   }
   console.log("File opened successfully!");
   console.log("Ready to read the file!");
   fs.read(fd, buf, 0, buf.length, 0, function(err, bytes){
      if (err){
         console.log(err);
      }

      // Output only read bytes
      if(bytes > 0){
         console.log(buf.slice(0, bytes).toString());
      }

      // Close file
      fs.close(fd, function(err){
         if (err){
            console.log(err);
         } 
         console.log("File closed successfully");
      });
   });
});

8, Intercept file

(1) Syntax format of intercepting files in asynchronous mode:

  • fs.ftruncate(fd, len, callback)

This method uses the file descriptor to read the file.
(2) The parameters are described as follows:

  • fd - through FS The file descriptor returned by the open () method.
  • len - length of file content interception.
  • Callback - callback function, no parameters.
// example
var fs = require("fs");
var buf = new Buffer.alloc(1024);

console.log("Ready to open the file!");
fs.open('input.txt', 'r+', function(err, fd) {
   if (err) {
       return console.error(err);
   }
   console.log("File opened successfully!");
   console.log("Intercept the file content within 10 bytes, and the excess will be removed.");
   
   // Intercept file
   fs.ftruncate(fd, 10, function(err){
      if (err){
         console.log(err);
      } 
      console.log("The file was intercepted successfully.");
      console.log("Read the same file"); 
      fs.read(fd, buf, 0, buf.length, 0, function(err, bytes){
         if (err){
            console.log(err);
         }

         // Output only read bytes
         if(bytes > 0){
            console.log(buf.slice(0, bytes).toString());
         }

         // Close file
         fs.close(fd, function(err){
            if (err){
               console.log(err);
            } 
            console.log("File closed successfully!");
         });
      });
   });
});

9, Delete file

(1) Delete the syntax format of the file:

  • fs.unlink(path, callback)

(2) The parameters are described as follows:

  • Path - file path.
  • Callback - callback function, no parameters.
// example
var fs = require("fs");

console.log("Ready to delete file!");
fs.unlink('input.txt', function(err) {
   if (err) {
       return console.error(err);
   }
   console.log("File deleted successfully!");
});

10, Create directory

(1) Syntax format for creating a directory:

  • fs.mkdir(path[, options], callback)
    (2) The parameters are described as follows:
  • Path - file path.
  • The options parameter can be:
    • recursive - whether to create a directory recursively. The default is false.
    • mode - set the directory permission. The default is 0777.
  • Callback - callback function, no parameters.
// example
var fs = require("fs");
// tmp directory must exist
console.log("Create directory /tmp/test/");
fs.mkdir("/tmp/test/",function(err){
   if (err) {
       return console.error(err);
   }
   console.log("Directory created successfully.");
});

// You can add the recursive: true parameter, regardless of whether the created directories / tmp and / tmp/a exist:
fs.mkdir('/tmp/a/apple', { recursive: true }, (err) => {
  if (err) throw err;
});

11, Read directory

(1) Syntax format of reading Directory:

  • fs.readdir(path, callback)

(2) The parameters are described as follows:

  • Path - file path.
  • Callback - callback function. The callback function takes two parameters: err, files. Err is the error information and files is the file array list under the directory.
// example
var fs = require("fs");

console.log("see /tmp catalogue");
fs.readdir("/tmp/",function(err, files){
   if (err) {
       return console.error(err);
   }
   files.forEach( function (file){
       console.log( file );
   });
});

12, Delete directory

(1) Syntax format of delete directory:

  • fs.rmdir(path, callback)

(2) The parameters are described as follows:

  • Path - file path.
  • Callback - callback function, no parameters.
// example
var fs = require("fs");
// Create an empty / tmp/test directory before execution
console.log("Preparing to delete directory /tmp/test");
fs.rmdir("/tmp/test",function(err){
   if (err) {
       return console.error(err);
   }
   console.log("read /tmp catalogue");
   fs.readdir("/tmp/",function(err, files){
      if (err) {
          return console.error(err);
      }
      files.forEach( function (file){
          console.log( file );
      });
   });
});

13, Document module method reference manual

methoddescribe
fs.rename(oldPath, newPath, callback)Asynchronous rename() The callback function has no parameters, but may throw an exception.
fs.ftruncate(fd, len, callback)Asynchronous ftruncate() The callback function has no parameters, but may throw an exception.
fs.ftruncateSync(fd, len)Sync ftruncate()
fs.truncate(path, len, callback)Asynchronous truncate() The callback function has no parameters, but may throw an exception.
fs.truncateSync(path, len)Synchronize
fs.chown(path, uid, gid, callback)Asynchronous chown() The callback function has no parameters, but may throw an exception.
fs.chownSync(path, uid, gid)Sync chown()
fs.fchown(fd, uid, gid, callback)Asynchronous fchown() The callback function has no parameters, but may throw an exception.
fs.fchownSync(fd, uid, gid)Sync fchown()
fs.lchown(path, uid, gid, callback)Asynchronous lchown() The callback function has no parameters, but may throw an exception.
fs.lchownSync(path, uid, gid)Sync lchown()
fs.chmod(path, mode, callback)Asynchronous chmod() The callback function has no parameters, but may throw an exception.
fs.chmodSync(path, mode)Synchronize chmod()
fs.fchmod(fd, mode, callback)Asynchronous fchmod() The callback function has no parameters, but may throw an exception.
fs.fchmodSync(fd, mode)Sync fchmod()
fs.lchmod(path, mode, callback)Asynchronous lchmod() The callback function has no parameters, but may throw an exception. Only available on Mac OS X.
fs.lchmodSync(path, mode)Sync lchmod()
fs.stat(path, callback)Asynchronous stat() The callback function has two parameters err, stats, and stats is FS Stats object.
fs.lstat(path, callback)Asynchronous lstat() The callback function has two parameters err, stats, and stats is FS Stats object.
fs.fstat(fd, callback)Asynchronous fstat() The callback function has two parameters err, stats, and stats is FS Stats object.
fs.statSync(path)Sync stat() Return FS An instance of stats.
fs.lstatSync(path)Synchronous lstat() Return FS An instance of stats.
fs.fstatSync(fd)Synchronous fstat() Return FS An instance of stats.
fs.link(srcpath, dstpath, callback)Asynchronous link() The callback function has no parameters, but may throw an exception.
fs.linkSync(srcpath, dstpath)Sync link()
fs.symlink(srcpath, dstpath[, type], callback)Asynchronous symlink() The callback function has no parameters, but may throw an exception. The type parameter can be set to 'dir', 'file', or 'junction' (the default is' file ').
fs.symlinkSync(srcpath, dstpath[, type])Sync symlink()
fs.readlink(path, callback)Asynchronous readlink() The callback function has two parameters err and linkstring.
fs.realpath(path[, cache], callback)Asynchronous realpath() The callback function has two parameters err and resolvedpath.
fs.realpathSync(path[, cache])Synchronize realpath(). Returns the absolute path.
fs.unlink(path, callback)Asynchronous unlink() The callback function has no parameters, but may throw an exception.
fs.unlinkSync(path)Sync unlink()
fs.rmdir(path, callback)Asynchronous rmdir() The callback function has no parameters, but may throw an exception.
fs.rmdirSync(path)Synchronize rmdir()
fs.mkdir(path[, mode], callback)S asynchronous mkdir(2) The callback function has no parameters, but may throw an exception. The default access permission is 0777.
fs.mkdirSync(path[, mode])Synchronize mkdir()
fs.readdir(path, callback)Asynchronous readdir(3) Read the contents of the directory.
fs.readdirSync(path)Synchronize readdir() Returns a list of file arrays.
fs.close(fd, callback)Asynchronous close() The callback function has no parameters, but may throw an exception.
fs.closeSync(fd)Synchronize close()
fs.open(path, flags[, mode], callback)Open file asynchronously.
fs.utimes(path, atime, mtime, callback)
fs.utimesSync(path, atime, mtime)Modify the file timestamp, and the file passes through the specified file path.
fs.futimes(fd, atime, mtime, callback)
fs.futimesSync(fd, atime, mtime)Modify the file timestamp and specify it through the file descriptor.
fs.fsync(fd, callback)Asynchronous fsync The callback function has no parameters, but may throw an exception.
fs.fsyncSync(fd)Sync fsync
fs.write(fd, buffer, offset, length[, position], callback)Writes the contents of the buffer to the file specified by the file descriptor.
fs.write(fd, data[, position[, encoding]], callback)Write the file contents through the file descriptor fd.
fs.writeSync(fd, buffer, offset, length[, position])Synchronous version of FS write().
fs.writeSync(fd, data[, position[, encoding]])Synchronous version of FS write().
fs.read(fd, buffer, offset, length, position, callback)Read the contents of the file through the file descriptor fd.
fs.readSync(fd, buffer, offset, length, position)Synchronous version of FS read.
fs.readFile(filename[, options], callback)Read file contents asynchronously.
fs.readFileSync(filename[, options])
fs.writeFile(filename, data[, options], callback)Write file contents asynchronously.
fs.writeFileSync(filename, data[, options])Synchronous version of FS writeFile.
fs.appendFile(filename, data[, options], callback)Asynchronously append file contents.
fs.appendFileSync(filename, data[, options])The synchronization version of FS appendFile.
fs.watchFile(filename[, options], listener)View the modification of the file.
fs.unwatchFile(filename[, listener])Stop viewing the modification of filename.
fs.watch(filename[, options][, listener])View the modification of filename. Filename can be a file or directory. Return FS Fswatcher object.
fs.exists(path, callback)Detects whether the given path exists.
fs.existsSync(path)Synchronous version of FS exists.
fs.access(path[, mode], callback)Test the user permissions of the specified path.
fs.accessSync(path[, mode])Synchronous version of FS access.
fs.createReadStream(path[, options])Returns a ReadStream object.
fs.createWriteStream(path[, options])Returns the WriteStream object.
fs.symlink(srcpath, dstpath[, type], callback)Asynchronous symlink() The callback function has no parameters, but may throw an exception.

Topics: Linux kafka Zookeeper Back-end