Fs module is one of the core modules of Node.js module, which provides basic methods to manipulate files and directories in accordance with POSIX specification. These methods come in both asynchronous and synchronous forms. In I/O intensive applications, asynchronous invocation is recommended to avoid blocking the entire application.

The first argument to the callback of all asynchronous methods is an IO error object:

/** synchronously call the method ***/
const fs=require('fs');

fs.unlinkSync('/f2');
console.log('succ');
Copy the code
/** Asynchronously call the method **/
const fs=require('fs');

fs.unlink('/f1',(err)=>{
	if(err)throw err;
  console.log('succ');
})
Copy the code

File pattern

In a Unix-like file system, the following operation permissions are defined to control different user permissions on files and directories:

R: Read, corresponding to 4 w: Write, corresponding to 2 x: eXecute, corresponding to 1 Users are classified into the following types: U: User, indicating the file owner G: Group, indicating other members of the file owner’s Group O: Other: indicates Other users

-rwx------	700The file owner can read, write, and execute files. -rwxr--r--744The file owner has read, write, and execute permissions, and other users have read permissions. -rw-rw-r--664File owners and group users can read and write files, while other users can read files DRWX --x--x711The owner of a directory has the read/write permission and access permission. Other users can only access the directory.Copy the code

Commonly used class

The class name instructions
fs.Stats File or directory statistics description object
fs.ReadStream The implementation object of the stream. Readable interface
fs.WriteStream Stream.writeable Interface implementation object
fs.FSWatcher File monitor object that can be used to monitor file modifications

Commonly used method

The method name instructions
Fs. The mkdir () Create a directory
Fs. Rmdir () Delete the directory
Fs. ReadFile () Reading file contents
Fs. WriteFile () Write content to the file
Fs. ApendFile () Appends content to a file
Fs. Unlink () Delete the file
Fs. Rename () Rename file

File Information Statistics

The fs.stat() and fs.statsync () methods are used to return a file or directory statistics object (type fs.stats).

const fs=require('fs');
fs.stat("./app.log",(err,stats)=>{
    if(err) throw err;
    console.log(stats);
  	console.log(stats.isFile())
})

/**** Displays the obtained information *******/
{
  dev: 1786362065.mode: 33206.nlink: 1.uid: 0.gid: 0.rdev: 0.blksize: 4096.ino: 1407374883658375.size: 12.blocks: 0.atimeMs: 1572344727794.7805.mtimeMs: 1572344727414.4744.ctimeMs: 1572344727414.4744.birthtimeMs: 1572344727413.4426.atime: 2019- 10- 29T10:25:27.795Z,
  mtime: 2019- 10- 29T10:25:27.414Z,
  ctime: 2019- 10- 29T10:25:27.414Z,
  birthtime: 2019- 10- 29T10:25:27.413Z
}

true
Copy the code

The Fs. Stats object also provides the following methods to check the physical properties of a file:

The method name instructions
stats.isFile() File or not
stats.isDireCtory() Directory or not
stats.isBlockDevice() Whether the device is a block device, such as a disk
stats.isCharacterDevice() Whether it is a character device, such as a keyboard
stats.isFIFO() Whether it is a FIFO device, such as a printer
stats.isSocket() Whether the file is a Socket file
const path='./htdocs';
fs.stat(path,(err,stats)=>{
    if(err){
        fs.mkdir(path);
    }else{
        fs.readdir(path,(err,list)=>{
            console.log(list)
        })
    }
})
Copy the code

Operating directory

The method name instructions
Fs.mkdir (path[,mode], callback) Create the specified directory (mode = file permission)
Fs. MkdirSync (path [, mode) Create a specified directory
fs.rmdir(path,callback) Deleting a specified directory
fs.rmdirSync(path) Deleting a specified directory
fs.readdir(path[,options],callback) Read the contents of a directory
fs.readdirSync(path[,options]) Read the contents of a directory

Create a htdocs directory with read/write and execute permissions for the current user, other members of the current user’s group, and other members:

const fs=require('fs');
fs.mkdir('./htdocs'.777,(err)=>{
    if(err)throw err;
    console.log("Directory created successfully!");
})
Copy the code

Read the contents of htdocs directory:

fs.readdir("./htdocs",(err,list)=>{
    if(err)throw err;
    console.log(list);
});
//[ 'img','index.html' ]
Copy the code

Delete the img folder in the htdocs directory:

fs.rmdir('./htdocs/img',(err)=>{
    if(err) throw err;
    console.log("Directory deleted successfully!)})Copy the code

Read and write the entire contents of the file

For files with a small amount of data, you can read and write all the contents at one time.

The method name instructions
Fs.readfile (file[,options], callback) Reading file contents
Fs. WriteFile (file, data [options], callback) Write the content
fs.apendFile(file,data[,options],callback) Additional content

Read file contents:

const path='./htdocs/index.html';
fs.readFile(path,(err,data)=>{
    if(err)throw err;
    console.log(data);
    console.log(data.toString())
})
Copy the code

Write to a file:

const path='./htdocs/index.html';
var data="

Hello world!

"
fs.writeFile(path,data,(err)=>{ if(err)throw err; console.log("Write data complete!"); }) Copy the code

Note: If the file does not exist, the writeFile method automatically creates the file. If the target file exists, this method overwrites all the original content.

Append to file:

const path='./htdocs/index.html';
var data="

I'm fine!

"
fs.appendFile(path,data,(err)=>{ if(err)throw err; console.log("Append data complete!"); }) Copy the code

Note: If the target file does not exist, the appendFile method creates the file automatically; If the target file exists, the method appends new content to the original content.

Read and write parts of a file

To install some contents of a diarrhea File, perform the following steps: (1) Open a specified File and obtain the corresponding “File Descriptors”. (2) Read or write the contents of a specified part of the File. (3) Close the file for other processes to use.

The method name instructions
Fs.open (path[,mode], callback) Open the file
Fs. Read (fd, buffer, offset, length, potion, callback) Read the file (offset is the storage offset of buffer, length is the maximum length of data stored in buffer, option reads from the position in the file)
fs.write(fd,offset,length[,position],callback) Write a file
fs.close(fd,callback) Close the file

Read part of the city:

const src='./htdocs/index.html';
fs.open(src,(err,fd)=>{
    if(err)throw err;
    const buf=Buffer.alloc(1024);
    fs.read(fd,buf,0.1024.0,(err,bytesRead,buffer)=>{
        if(err)throw err;
      	console.log("Actual number of moral bytes read: %d",bytesRead);
        console.log(buffer.toString('UTF-8'.0,bytesRead));
        fs.close(fd,(err)=>{
            if(err)throw err;
            console.log('File closed! ')}); })});/ / 45
//

Hello world!

I'm fine!

// File closed! Copy the code

Write part of the content:

const src='./htdocs/index.html';
fs.open(src,'w',(err,fd)=>{
    if(err)throw err;
    const buf=Buffer.from("< h3 > is really good! ");
    fs.write(fd,buf,0.'UTF-8',(err,bytesRead,string)=>{
        if(err)throw err;
        console.log("Write some content successfully!");
        console.log("Write bytes: %d, write content: %s",bytesRead,string)
        fs.close(fd,(err)=>{
            if(err)throw err;
            console.log('File closed! ')}); })});// Write some content successfully!

// File closed! Copy the code

Streaming operations of files

A Stream, “Stream,” is an ordered set of bytes or character set data with a starting and ending point.

In Node.js, the stream module’s implementation object of the Readable interface can read some of the file data temporarily stored in the buffer, such as fs.ReadStream, http.IncomingMessage, net.Socket, process.stdin, etc. These objects all inherit from the EventMitter class, which can trigger various stream read-related events during data reading.

Any implementation object of the Stream module’s Writable interface can be used to write data to the buffer, and then output to the physical medium when the buffer is full: Fs. WriteStream, HTTP. ClienrRequest, http.ServerResponse, net.Socket, process.stdout, etc.; These objects all inherit from the EventMitter class, which can trigger various read-write events during writing out data.

Input stream object

The Stream.Readable object can emit the following events:

The event name instructions
readable Triggered when data can be read from the stream
data Triggered when data is read
end Triggered when the end of the stream is read
error Triggered when a read error occurs
close Triggered when the stream is closed

The Stream.Readable object can perform the following operations:

The method name instructions
read() Read the data
setEncoding() Setting character encoding
pause() Stop reading
resume() Continue to read
pipe() Set up a data channel
unpipe() Cancels the set data channel
const fs=require('fs');

var read=fs.createReadStream('./htdocs/1.mp4');

var total=0;
read.on("data",(buf)=>{
    console.log("Data length: %d",buf.length);
    total+=buf.length;
})
read.on("end",(err)=>{
    if(err)throw err;
    console.log("File reading finished!");
    console.log("Total bytes read: %d",total);
})
read.on("close",(err)=>{
    if(err)throw err;
    console.log("Stream closed successfully!")})// Data length: 65536
// Data length: 65536
/ /...
// Data length: 65536
// Data length: 65536
// Data length: 65536
// Data length: 50848
// End of file reading!
// Read the total number of bytes: 117819040
// Stream closed successfully!
Copy the code

Output stream object

The stream.writeable object can fire the following events:

The event name instructions
drain Triggered when the output buffer has been emptied
finish Fired when the end() method writes out all data to the buffer
pipe Emitted when pipe() is called by the object used to read data
unpipe Raised when unpipe() is called by the object used to read data
error Triggered when an error occurs in the output procedure

The stream.writeable object can do the following:

The method name instructions
write() Write the data
end() This method clears the output buffer when no more data needs to be output

Implement a file copy function with readStream and writeStream:

const fs=require('fs');

var read=fs.createReadStream('./htdocs/1.mp4');
var write=fs.createWriteStream("./htdocs/1_copy.mp4");
var total=0;
read.on("data",(buf)=>{
    console.log("Data length: %d",buf.length);
    total+=buf.length;
    write.write(buf,0,buf.length);
})
read.on("end",(err)=>{
    if(err)throw err;
    console.log("File reading finished!");
    console.log("Total bytes read: %d",total);
    write.end();
});
read.on("close",(err)=>{
    if(err)throw err;
    console.log("Stream closed successfully!")
})
write.on("finish",(err)=>{
    if(err)throw err;
    console.log("File written!")})// Data length: 65536
/ /...
// Data length: 50848
// End of file reading!
// Read the total number of bytes: 117819040
// The file is written!
// Stream closed successfully!
Copy the code

Use the pipe

Pipe: a Pipe that can be used to automatically read all data from a Readable object and write it to a specified Writeable object.

const fs=require("fs");

const src="./htdocs/index.html";
const dest="./backup/index.html";

var read=fs.createReadStream(src);
var write=fs.createWriteStream(dest);

read.pipe(write);		// Use pipes for automatic reading and writing
reader.on("end",(err)=>{
	if(err)throw err;
  console.log("File has been copied!")})Copy the code