Document manipulation in the base section of node

Posted by mlummus on Sun, 21 Jul 2019 07:06:16 +0200

Write in front

File operations in node are quite frequent, and there are many APIs that provide various operations on files and folders. The following is a case study of common APIs to understand their specific usage.

A read file fs.readFile(), fs.readFileSync()

fs file operation basically includes two ways of synchronization and asynchrony, which will be described in the following section for each function at the same time.

Asynchronous fs.readFile (filename, [optional parameters, encoding, such as'utf-8'],callback)

fs.readFile('/Users/kekobin/node-dir-test/util.js', (err, buffer) => {
    if(err) throw err;
    console.log(buffer.toString())
})   

callback callbacks contain err and buffer. By default, no encoding is transmitted. Buffer binary data is returned, but it can be passed through

buffer.toString()

Convert to a string. The reason why buffer is used by default is that binary stream occupies less memory, transmits and runs fast and has high performance.

Synchronize fs.readFileSync (filename, [optional parameters, encoding method, such as'utf-8'])

try {
    const buffer = fs.readFileSync('/Users/kekobin/node-dir-test/util.js')
} catch(e) {}

fs.readFile() and fs.readFileSync() constantly buffer the read content into memory until the entire file is buffered. Therefore, fs.createReadStream() is generally used to replace streaming transmission when reading large or large files to reduce the pressure of memory.

Write file fs.writeFile() fs.writeFileSync()

Asynchronous fs.writeFile (filename, content written, [optional parameters, encoding, such as'utf-8'],callback)

fs.writeFile('/Users/kekobin/node-dir-test/util.js','test writing file', (err) => {
    if(err) { console.log('fail to write to file');return; }
    console.log('Write file successfully');
})   

The callback callback has only the err parameter, which indicates whether the write was successful.

Synchronize fs.writeFileSync (filename, content written, [optional parameters, encoding method, such as'utf-8'])

try {
    const err = fs.writeFileSync('/Users/kekobin/node-dir-test/util.js','test writing file')   
} catch(e) {}

Create folder fs.mkdir() fs.mkdirSync()

Asynchronous fs.mkdir (file name, permission, callback)

fs.mkdir('/Users/kekobin/node-dir-test/test-dir',0777, (err) => {
    if(err) { console.log('Failed to create folder');return; }
    console.log('Successful folder creation');
})   

"Permission" refers to whether the created folder is readable, writable, etc.

Synchronize fs.mkdirSync (filename, permission)

try {
    const err = fs.mkdirSync(''/Users/kekobin/node-dir-test/test-dir',0777)   
} catch(e) {}

Get file or folder status fs.stat() fs.statSync()

These two APIs are often used to determine whether files or folders are being processed

Asynchronous fs.stat (filename or folder name)

fs.stat('/Users/kekobin/node-dir-test/test-dir',(err, stats) => {
    if(err) throw err;
    if(stats.isFile()) {}
    if(stats.isDirectory()) {}
})   

The parameter stats in the callback is an object containing file or folder information. The most commonly used method is to use stats.isFile() to determine whether a file is a file or not, and stats.isDirectory() to determine whether a folder is a folder.

Synchronize fs.statSync (filename or folder name)

try {
    const stats = fs.statSync('/Users/kekobin/node-dir-test/test-dir')   
} catch(e) {}

Since fs.exists() has been abandoned, it is also possible to judge whether a file or folder exists or not by reading a folder, judging whether stats.isDirectory() is true or true, otherwise it does not exist.

5. readdir(), readdirSync()

These two APIs return an array of included files and subdirectories.

Asynchronous fs. readdir (folder name)

const dir = '/Users/kekobin/node-dir-test/';
fs.readdir(dir, function (err, files) {
    if (err) {
      throw err;
      return;
    }

    files.forEach( (filename, index) => {
        const fullname = path.join(dir,filename);
        fs.stat(fullname, (err, stats) => {
            if(err) throw err;
            if(stats.isDirectory()) {

            }
            if(stats.isFile()) {
            }
        })
    });
});  

Generally used for traversing folders, generating file trees and other operations.

Synchronize fs. readdirSync (folder name)

try {
    const files = fs.readdirSync(dir)   
} catch(e) {}

Create file read stream fs. createReadStream (file name)

It is often used to open large text files and create a data stream for reading operations. The so-called large text file refers to the large size of the text file, which can not be loaded into the cache of the reading operation, and can only be sent several times. Each sending will trigger a data event, and the end of sending will trigger an end event.

let result = '';
fs.createReadStream('/Users/kekobin/node-dir-test/util.js')
.on('data', (data) => {
    result += data;
})
.on('end', () => {
    console.log('Get what the final file reads', result);
})

Create file write stream fs. createWriteStream (file name)

Create a write data stream object, whose write method is used to write data, and the end method is used to end the write operation.

const out = fs.createWriteStream(fileName, {
    encoding: 'utf8'
});
out.write(str);
out.end();

For example, createWriteStream and createReadStream cooperate to copy large files.

function fileCopy(filename1, filename2, done) {
    var input = fs.createReadStream(filename1);
    var output = fs.createWriteStream(filename2);
  
    input.on('data', function(d) { output.write(d); });
    input.on('error', function(err) { throw err; });
    input.on('end', function() {
      output.end();
      if (done) done();
    });
}
// Copy util.js to util2.js
fileCopy('/Users/kekobin/node-dir-test/util.js', '/Users/kekobin/node-dir-test/util2.js', function() {
    console.log('end')
})

8 Delete file fs.unlink() fs.unlinkSync()

Asynchronous fs.unlink (filename)

fs.unlink('/Users/kekobin/node-dir-test/util2.js', function(err){
    if(err) throw err;
    console.log('Successful deletion of files');
}); 

Synchronize fs.unlinkSync (filename)

try { fs.unlinkSync('/Users/kekobin/node-dir-test/util2.js') } catch(){}

9 Delete directory fs.rmdir() fs.rmdirSync()

Asynchronous fs.rmdir (folder name, callback)

fs.rmdir('/Users/kekobin/node-dir-test/test-dir', function(err){
    if(err) throw err;
    console.log('Successful directory deletion');
}); 

Synchronize fs.rmdirSync (filename)

try { fs.rmdirSync('/Users/kekobin/node-dir-test/test-dir') } catch(){}

Example: Read all files in a directory synchronously

const getFiles = function(dir){
    const results = [];
    const files = fs.readdirSync(dir, 'utf8');

    files.forEach(function(file){
        const fullname = path.resolve(dir, file);
        const stats = fs.statSync(fullname);

        if(stats.isFile()){
            results.push(fullname);
        }else if(stats.isDirectory()){
            results = results.concat( getFiles(fullname) );
        }
    });

    return results;
};

const files = getFiles('/Users/kekobin/node-dir-test/');

This article is included in the personal Github https://github.com/kekobin/bl... Welcome to Startha. Support the original, without my consent, please do not reprint!

Topics: node.js encoding github less