node.js 17 file operation

This article refers to the original- http://bjbsair.com/2020-03-22/tech-info/2819/ After talking about the module concept, let's take a look at the file operations in node.js in this article. The API of file operation is in fs module, fs is called "File System".

Most programming languages provide file manipulation, and node.js is no exception. Let's take a look at the judgment of file / directory, adding, deleting, reading, writing, renaming and copying of files.

node.js file operation

Node.js has a big feature, which is asynchronous operation. This is the same in file operations. Some languages judge whether files or directories will not use asynchrony, but node.js is different. It uses asynchrony to process through callback function.

So learning node.js must have the concept of asynchrony, and callback function must also be understood. There will be a special explanation about asynchronous processing later.

How to determine whether the incoming path is a file or a directory

First, we need to introduce the FS module, and then judge whether the object is a file or a directory through the callback function in the fs.stat method.

Take a look at the sample code. I always think that writing code without comments is to reject teamwork and knowledge sharing.

//1. Introduce fs module  
const fs = require('fs');  
  
//2. Call the fs.stat method, pass in the file, and process the data object through the callback function  
fs.stat('./package.json', (err,data)=>{  
    if(err){  
        console.log(err)  
        return  
    }  
      
    //3. Call isFile() method to determine whether it is a file  
    console.log(`is file: ${data.isFile()}`)  
    //4. Call isDirectory() method to determine whether it is a directory  
    console.log(`is directory: ${data.isDirectory()}`)  
})

Since package.json is a file, isFile:true is printed out. The output results are as follows:

D:\Projects\nodejs\NodeDemo>node app.js  
  
is file: true  
  
is directory: false

Create directory

The "Fs" module also needs to be introduced. Since all file operations need to introduce the "Fs" module, the following examples will not emphasize it. Then call the fs.mkdir() method to create.

//1. Introduce fs module  
const fs = require('fs');  
//2. Call mkdir() method to create directory  
fs.mkdir('./testDir', (err)=>{  
    if(err){  
        console.log(err);  
        return;  
    }  
    console.log('Create directory complete')  
})

Create and write files

When creating a file, you can directly create it through the method fs.writeFile() and write the content.

//1. Introduce fs module  
const fs = require('fs');  
//2. Create and write files  
fs.writeFile('./test.txt','Hello, node.js', (err)=>{  
    if(err){  
        console.log(err)  
        return  
    }  
    console.log('Write file created successfully')  
})

The above code example creates the file test.txt and writes "Hello, node.js" in the file.

Add file content

If it is not enough to write the contents of the file at the time of creation, any language dealing with the file needs to provide methods to add the contents of the file. node.js provides the fs.appendFile() method.

//1. Introduce fs module  
const fs = require('fs');  
//2. Add document content  
fs.appendFile('./test.txt', '\r\nHello Vincent', (err)=>{  
    if(err){  
        console.log(err)  
        return;  
    }  
    console.log('appendFile Success')  
})

At this time, if we open the test.txt file, we will see the "Hello, node.js" written at creation time and the "Hello Vincent" added this time. Where "\ r\n" is carriage return and line feed.

Hello, node.js

Hello Vincent

Read file contents

Method: fs.readFile() is an asynchronous method.

An example is as follows.

//1. Introduce fs module  
const fs = require('fs');  
//2. Read the contents of the file  
fs.readFile('./test.txt', (err, data)=>{  
    if(err){  
        consolog.log(err)  
        return  
    }  
    console.log(data.toString())  
})

Read directory

Call method: fs.readdir(), and output subdirectories and files under the directory after reading.

Sample code

//1. Introduce fs module  
const fs = require('fs');  
//2. read  
fs.readdir('.', (err, data)=>{  
    if(err){  
        console.log(err)  
        return  
    }  
    console.log(data)  
})

Output is as follows

D:\Projects\nodejs\NodeDemo>node app.js  
[ 'app.js', 'testDir', 'package.json', 'test.txt' ]

rename

Call method fs.rename(). This method should be noted that, on the one hand, rename. On the other hand, if the target file is not in the same directory, this method is actually to move the file to the target directory.

//1. Introduce fs module  
const fs = require('fs');  
//2. Rename and move the file (in this case, move the file)  
fs.rename('./test.txt', './testDir/test.txt', (err) => {  
    if(err){  
        console.log(err)  
        return  
    }  
    console.log('Move file succeeded')  
})

The above example moves the test.txt file in the current directory to the. / testDir directory.

Delete files

Calling method: fs.unlink()

Sample code

//1. Introduce fs module  
const fs = require('fs');  
//2. Delete files  
fs.unlink('./test.txt', (err)=>{  
    if(err){  
        console.log(err)  
        return  
    }  
    console.log('Delete file succeeded')  
})

Delete directory

Call method: fs.rmdir(). It should be noted that the directory can only be deleted if it is an empty directory, otherwise an error will be reported. Therefore, you need to traverse the directory first, delete the files or subdirectories under the directory, and then delete the current directory. If there are subdirectories under subdirectories, you need to recurse. Through npm, you can also download another file processing module, which can directly delete directories. Of course, the code to delete files and subdirectories has been encapsulated in it.

Here is an example of an empty directory deletion

//1. Introduce fs module  
const fs = require('fs');  
//2. Delete directory  
fs.rmdir('./testDir', (err)=>{  
    if(err){  
        console.log(err)  
        return  
    }  
    console.log('Delete directory succeeded')  
})

Byte stream

Before entering the file copy, we need to understand the byte stream. For reading and writing large files, the byte stream is used.

  • Use byte stream to read file: fs.createReadStream()
  • Write file using byte stream: fs.createWriteStream()

Copy file

First, you need to read the source file using a byte stream, then create a write file stream, and finally copy it through the pipe() method.

const fs = require('fs')  
var readStream = fs.createReadStream('./test.MOV')  
  
var writeStream = fs.createWriteStream('./data/copied.MOV')  
readStream.pipe(writeStream)

The code is small, simple and convenient, and the whole file is copied successfully.

summary

node.js is simple and convenient for file processing in general, with less code. Asynchronous operation runs through the real fs module, and there is a little challenge in the actual coding work. As mentioned above, we can encapsulate fs module, write our own file operation module, encapsulate directory deletion, etc. There are also some file operation modules in npm management.

Welcome to leave a message.

node.js will be updated continuously, including http, url, database operation, etc. This article refers to the original- http://bjbsair.com/2020-03-22/tech-info/2819/ After talking about the module concept, let's take a look at the file operations in node.js in this article. The API of file operation is in fs module, fs is called "File System".

Most programming languages provide file manipulation, and node.js is no exception. Let's take a look at the judgment of file / directory, adding, deleting, reading, writing, renaming and copying of files.

node.js file operation

Node.js has a big feature, which is asynchronous operation. This is the same in file operations. Some languages judge whether files or directories will not use asynchrony, but node.js is different. It uses asynchrony to process through callback function.

So learning node.js must have the concept of asynchrony, and callback function must also be understood. There will be a special explanation about asynchronous processing later.

How to determine whether the incoming path is a file or a directory

First, we need to introduce the FS module, and then judge whether the object is a file or a directory through the callback function in the fs.stat method.

Take a look at the sample code. I always think that writing code without comments is to reject teamwork and knowledge sharing.

//1. Introduce fs module  
const fs = require('fs');  
  
//2. Call the fs.stat method, pass in the file, and process the data object through the callback function  
fs.stat('./package.json', (err,data)=>{  
    if(err){  
        console.log(err)  
        return  
    }  
      
    //3. Call isFile() method to determine whether it is a file  
    console.log(`is file: ${data.isFile()}`)  
    //4. Call isDirectory() method to determine whether it is a directory  
    console.log(`is directory: ${data.isDirectory()}`)  
})

Since package.json is a file, isFile:true is printed out. The output results are as follows:

D:\Projects\nodejs\NodeDemo>node app.js  
  
is file: true  
  
is directory: false

Create directory

The "Fs" module also needs to be introduced. Since all file operations need to introduce the "Fs" module, the following examples will not emphasize it. Then call the fs.mkdir() method to create.

//1. Introduce fs module  
const fs = require('fs');  
//2. Call mkdir() method to create directory  
fs.mkdir('./testDir', (err)=>{  
    if(err){  
        console.log(err);  
        return;  
    }  
    console.log('Create directory complete')  
})

Create and write files

When creating a file, you can directly create it through the method fs.writeFile() and write the content.

//1. Introduce fs module  
const fs = require('fs');  
//2. Create and write files  
fs.writeFile('./test.txt','Hello, node.js', (err)=>{  
    if(err){  
        console.log(err)  
        return  
    }  
    console.log('Write file created successfully')  
})

The above code example creates the file test.txt and writes "Hello, node.js" in the file.

Add file content

If it is not enough to write the contents of the file at the time of creation, any language dealing with the file needs to provide methods to add the contents of the file. node.js provides the fs.appendFile() method.

//1. Introduce fs module  
const fs = require('fs');  
//2. Add document content  
fs.appendFile('./test.txt', '\r\nHello Vincent', (err)=>{  
    if(err){  
        console.log(err)  
        return;  
    }  
    console.log('appendFile Success')  
})

At this time, if we open the test.txt file, we will see the "Hello, node.js" written at creation time and the "Hello Vincent" added this time. Where "\ r\n" is carriage return and line feed.

Hello, node.js

Hello Vincent

Read file contents

Method: fs.readFile() is an asynchronous method.

An example is as follows.

//1. Introduce fs module  
const fs = require('fs');  
//2. Read the contents of the file  
fs.readFile('./test.txt', (err, data)=>{  
    if(err){  
        consolog.log(err)  
        return  
    }  
    console.log(data.toString())  
})

Read directory

Call method: fs.readdir(), and output subdirectories and files under the directory after reading.

Sample code

//1. Introduce fs module  
const fs = require('fs');  
//2. read  
fs.readdir('.', (err, data)=>{  
    if(err){  
        console.log(err)  
        return  
    }  
    console.log(data)  
})

Output is as follows

D:\Projects\nodejs\NodeDemo>node app.js  
[ 'app.js', 'testDir', 'package.json', 'test.txt' ]

rename

Call method fs.rename(). This method should be noted that, on the one hand, rename. On the other hand, if the target file is not in the same directory, this method is actually to move the file to the target directory.

//1. Introduce fs module  
const fs = require('fs');  
//2. Rename and move the file (in this case, move the file)  
fs.rename('./test.txt', './testDir/test.txt', (err) => {  
    if(err){  
        console.log(err)  
        return  
    }  
    console.log('Move file succeeded')  
})

The above example moves the test.txt file in the current directory to the. / testDir directory.

Delete files

Calling method: fs.unlink()

Sample code

//1. Introduce fs module  
const fs = require('fs');  
//2. Delete files  
fs.unlink('./test.txt', (err)=>{  
    if(err){  
        console.log(err)  
        return  
    }  
    console.log('Delete file succeeded')  
})

Delete directory

Call method: fs.rmdir(). It should be noted that the directory can only be deleted if it is an empty directory, otherwise an error will be reported. Therefore, you need to traverse the directory first, delete the files or subdirectories under the directory, and then delete the current directory. If there are subdirectories under subdirectories, you need to recurse. Through npm, you can also download another file processing module, which can directly delete directories. Of course, the code to delete files and subdirectories has been encapsulated in it.

Here is an example of an empty directory deletion

//1. Introduce fs module  
const fs = require('fs');  
//2. Delete directory  
fs.rmdir('./testDir', (err)=>{  
    if(err){  
        console.log(err)  
        return  
    }  
    console.log('Delete directory succeeded')  
})

Byte stream

Before entering the file copy, we need to understand the byte stream. For reading and writing large files, the byte stream is used.

  • Use byte stream to read file: fs.createReadStream()
  • Write file using byte stream: fs.createWriteStream()

Copy file

First, you need to read the source file using a byte stream, then create a write file stream, and finally copy it through the pipe() method.

const fs = require('fs')  
var readStream = fs.createReadStream('./test.MOV')  
  
var writeStream = fs.createWriteStream('./data/copied.MOV')  
readStream.pipe(writeStream)

The code is small, simple and convenient, and the whole file is copied successfully.

summary

node.js is simple and convenient for file processing in general, with less code. Asynchronous operation runs through the real fs module, and there is a little challenge in the actual coding work. As mentioned above, we can encapsulate fs module, write our own file operation module, encapsulate directory deletion, etc. There are also some file operation modules in npm management.

Welcome to leave a message.

node.js will be updated continuously, including http, url, database operation, etc.

Tags: Programming JSON npm less

Posted on Tue, 24 Mar 2020 11:54:46 -0400 by BLottman