Node.js - Filesystem

Node.js provides a set of UNIX-like (POSIX) standard file manipulation APIs. The Node import file system module (fs) syntax is as follows:

var fs = require("fs")

asynchronous and synchronous

The methods in the Node.js file system (fs module) module have asynchronous and synchronous versions. For example, the function to read file content has asynchronous fs.readFile() and synchronous fs.readFileSync().

The last parameter of the asynchronous method function is a callback function, and the first parameter of the callback function contains the error message (error).

It is recommended that you use asynchronous methods. Compared with synchronous methods, asynchronous methods have higher performance, faster speed, and no blocking.

example

Create an input.txt file with the following content:

菜鸟教程官网地址:www.runoob.com
文件读取实例

Create file.js file, the code is as follows:

var fs = require("fs");

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

// 同步读取
var data = fs.readFileSync('input.txt');
console.log("同步读取: " + data.toString());

console.log("程序执行完毕。");

The above code execution results are as follows:

$ node file.js 
同步读取: 菜鸟教程官网地址:www.runoob.com
文件读取实例

程序执行完毕。
异步读取: 菜鸟教程官网地址:www.runoob.com
文件读取实例

Next, let's take a closer look at the Node.js filesystem approach.

open a file

grammar

The syntax for opening a file in asynchronous mode is as follows:

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

parameter

Parameter usage instructions are as follows:

  • path  - the path to the file.

  • flags  - Behavior of file opening. See below for specific values.

  • mode  - set the file mode (permission), the default permission of file creation is 0666 (readable, writable).

  • callback  - callback function, with two parameters such as: callback(err, fd).

The flags parameter can have the following values:

Flag describe
r Open the file in read mode. An exception is thrown if the file does not exist.
r+ Open the file in read-write mode. An exception is thrown if the file does not exist.
rs Read the file synchronously.
rs+ Read and write files synchronously.
w Open the file in write mode, creating it if it does not exist.
wx Like 'w', but fails writing the file if the file path exists.
w+ Open the file in read-write mode, creating it if it does not exist.
wx+ Like 'w+', but fails to read or write the file if the file path exists.
a Open the file in append mode, creating it if it does not exist.
ax Like 'a', but file append fails if the file path exists.
a+ Open the file in read-append mode, creating the file if it does not exist.
ax+ Like 'a+', but file read append fails if the file path exists.

 example

Next, we create the file.js file and open the input.txt file for reading and writing. The code is as follows:

var fs = require("fs");

// 异步打开文件
console.log("准备打开文件!");
fs.open('input.txt', 'r+', function(err, fd) {
   if (err) {
       return console.error(err);
   }
  console.log("文件打开成功!");     
});

The above code execution results are as follows:

$ node file.js 
准备打开文件!
文件打开成功!

Get file information

grammar

The syntax format for obtaining file information in asynchronous mode is as follows:

fs.stat(path, callback)

parameter

Parameter usage instructions are as follows:

  • path  - the file path.

  • callback  - callback function with two parameters such as: (err, stats),  stats  is fs.Stats object.

After fs.stat(path) is executed, the instance of the stats class will be returned to its callback function. The relevant attributes of the file can be judged through the methods provided in the stats class. For example, to determine 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 the stats class are:

method describe
stats.isFile() Returns true if it is a file, otherwise returns false.
stats.isDirectory() Returns true if it is a directory, false otherwise.
stats.isBlockDevice() Returns true if it is a block device, false otherwise.
stats.isCharacterDevice() Returns true if it is a character device, false otherwise.
stats.isSymbolicLink() Returns true if it is a soft link, otherwise returns false.
stats.isFIFO() If it is FIFO, return true, otherwise return false. FIFO is a special type of command pipe in UNIX.
stats.isSocket() If it is a Socket return true, otherwise return false.

example

Next we create the file.js file, the code is as follows:

var fs = require("fs");

console.log("准备打开文件!");
fs.stat('input.txt', function (err, stats) {
   if (err) {
       return console.error(err);
   }
   console.log(stats);
   console.log("读取文件信息成功!");
   
   // 检测文件类型
   console.log("是否为文件(isFile) ? " + stats.isFile());
   console.log("是否为目录(isDirectory) ? " + stats.isDirectory());    
});

 The above code execution results are as follows:

$ node file.js 
准备打开文件!
{ 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) }
读取文件信息成功!
是否为文件(isFile) ? true
是否为目录(isDirectory) ? false

write to file

grammar

The syntax for writing files in asynchronous mode is as follows:

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

writeFile directly opens the file in w mode by default, so if the file exists, the content written by this method will overwrite the old file content.

parameter

Parameter usage instructions are as follows:

  • file  - a filename or file descriptor.

  • data  - the data to be written to the file, either a String (string) or a Buffer (buffer) object.

  • options  - The parameter is an object containing {encoding, mode, flag}. The default encoding is utf8, the mode is 0666, and the flag is 'w'

  • callback  - callback function, the callback function only contains the error message parameter (err), and returns when writing fails.

example

Next we create the file.js file, the code is as follows:

var fs = require("fs");

console.log("准备写入文件");
fs.writeFile('input.txt', '我是通 过fs.writeFile 写入文件的内容',  function(err) {
   if (err) {
       return console.error(err);
   }
   console.log("数据写入成功!");
   console.log("--------我是分割线-------------")
   console.log("读取写入的数据!");
   fs.readFile('input.txt', function (err, data) {
      if (err) {
         return console.error(err);
      }
      console.log("异步读取文件数据: " + data.toString());
   });
});

The above code execution results are as follows:

$ node file.js 
准备写入文件
数据写入成功!
--------我是分割线-------------
读取写入的数据!
异步读取文件数据: 我是通 过fs.writeFile 写入文件的内容

read file

grammar

The syntax for reading files in asynchronous mode is as follows:

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

This method uses a file descriptor to read a file.

parameter

Parameter usage instructions are as follows:

  • fd  - the file descriptor returned by the fs.open() method.

  • buffer  - the buffer to write the data to.

  • offset  - The write offset at which the buffer is written.

  • length  - the number of bytes to read from the file.

  • position  - the starting position of the file read, if the value of position is null, it will read from the position of the current file pointer.

  • callback  - callback function, with three parameters err, bytesRead, buffer, err is the error message, bytesRead indicates the number of bytes read, and buffer is the buffer object.

example

The content of the input.txt file is:

菜鸟教程官网地址:www.runoob.com

Next we create the file.js file, the code is as follows:

var fs = require("fs");
var buf = new Buffer.alloc(1024);

console.log("准备打开已存在的文件!");
fs.open('input.txt', 'r+', function(err, fd) {
   if (err) {
       return console.error(err);
   }
   console.log("文件打开成功!");
   console.log("准备读取文件:");
   fs.read(fd, buf, 0, buf.length, 0, function(err, bytes){
      if (err){
         console.log(err);
      }
      console.log(bytes + "  字节被读取");
      
      // 仅输出读取的字节
      if(bytes > 0){
         console.log(buf.slice(0, bytes).toString());
      }
   });
});

The above code execution results are as follows:

$ node file.js 
准备打开已存在的文件!
文件打开成功!
准备读取文件:
42  字节被读取
菜鸟教程官网地址:www.runoob.com

close file

grammar

The syntax for closing a file in asynchronous mode is as follows:

fs.close(fd, callback)

This method uses a file descriptor to read a file.

parameter

Parameter usage instructions are as follows:

  • fd  - the file descriptor returned by the fs.open() method.

  • callback  - callback function, no parameters.

example

The content of the input.txt file is

菜鸟教程官网地址:www.runoob.com

Next we create the file.js file, the code is as follows:

var fs = require("fs");
var buf = new Buffer.alloc(1024);

console.log("准备打开文件!");
fs.open('input.txt', 'r+', function(err, fd) {
   if (err) {
       return console.error(err);
   }
   console.log("文件打开成功!");
   console.log("准备读取文件!");
   fs.read(fd, buf, 0, buf.length, 0, function(err, bytes){
      if (err){
         console.log(err);
      }

      // 仅输出读取的字节
      if(bytes > 0){
         console.log(buf.slice(0, bytes).toString());
      }

      // 关闭文件
      fs.close(fd, function(err){
         if (err){
            console.log(err);
         } 
         console.log("文件关闭成功");
      });
   });
});

The above code execution results are as follows:

$ node file.js 
准备打开文件!
文件打开成功!
准备读取文件!
菜鸟教程官网地址:www.runoob.com
文件关闭成功

intercept file

grammar

The following is the syntax format for intercepting files in asynchronous mode:

fs.ftruncate(fd, len, callback)

This method uses a file descriptor to read a file.

parameter

Parameter usage instructions are as follows:

  • fd  - the file descriptor returned by the fs.open() method.

  • len  - the length of the file content interception.

  • callback  - callback function, no parameters.

example

The content of the input.txt file is:

site:www.runoob.com

Next we create the file.js file, the code is as follows:

var fs = require("fs");
var buf = new Buffer.alloc(1024);

console.log("准备打开文件!");
fs.open('input.txt', 'r+', function(err, fd) {
   if (err) {
       return console.error(err);
   }
   console.log("文件打开成功!");
   console.log("截取10字节内的文件内容,超出部分将被去除。");
   
   // 截取文件
   fs.ftruncate(fd, 10, function(err){
      if (err){
         console.log(err);
      } 
      console.log("文件截取成功。");
      console.log("读取相同的文件"); 
      fs.read(fd, buf, 0, buf.length, 0, function(err, bytes){
         if (err){
            console.log(err);
         }

         // 仅输出读取的字节
         if(bytes > 0){
            console.log(buf.slice(0, bytes).toString());
         }

         // 关闭文件
         fs.close(fd, function(err){
            if (err){
               console.log(err);
            } 
            console.log("文件关闭成功!");
         });
      });
   });
});

The above code execution results are as follows:

$ node file.js 
准备打开文件!
文件打开成功!
截取10字节内的文件内容,超出部分将被去除。
文件截取成功。
读取相同的文件
site:www.r
文件关闭成功

Guess you like

Origin blog.csdn.net/jewels_w/article/details/130661760