Methods and instances to implement file replication in node. js

  • 2020-03-30 03:11:09
  • OfStack

Node.js itself does not provide an API for directly copying files. If you want to copy files or directories with node. js, you need to use other apis. It is easier to copy individual files with readFile, writeFile, etc. If you are copying all the files in a directory, which may contain subdirectories, then you need a more advanced API.

flow

Streams are the way node. js moves data, streams in node. js are readable/writable, and both HTTP and file system modules are useful to streams. In the file system, when using the stream to read the file, a large file may not be read all at once, but will be read several times, read the time will respond to the data event, in the file is not read all can be read when the data operation. Similarly, large files are not written all at once when writing into the stream as they are when reading. This way of moving data is very efficient, especially for large files, where using a stream is much faster than waiting for the entire file to be read.

The pipe

You can use data events if you want to do full control when reading the stream and writing into the stream. But for simple file copying, read streams and write streams can be piped through.

Practical application:


var fs = require( 'fs' ),
    stat = fs.stat;


var copy = function( src, dst ){
    //Read all files/directories in the directory
    fs.readdir( src, function( err, paths ){
        if( err ){
            throw err;
        }
        paths.forEach(function( path ){
            var _src = src + '/' + path,
                _dst = dst + '/' + path,
                readable, writable;        
            stat( _src, function( err, st ){
                if( err ){
                    throw err;
                }
                //Determine if it is a file
                if( st.isFile() ){
                    //Create read stream
                    readable = fs.createReadStream( _src );
                    //Create write in stream
                    writable = fs.createWriteStream( _dst );   
                    //To transport the flow through a pipe
                    readable.pipe( writable );
                }
                //If it's a directory, it calls itself recursively
                else if( st.isDirectory() ){
                    exists( _src, _dst, copy );
                }
            });
        });
    });
};
//You need to determine if the directory exists before you copy it, and if it does not, you need to create the directory first
var exists = function( src, dst, callback ){
    fs.exists( dst, function( exists ){
        //existing
        if( exists ){
            callback( src, dst );
        }
        //There is no
        else{
            fs.mkdir( dst, function(){
                callback( src, dst );
            });
        }
    });
};
//Copy directory
exists( './src', './build', copy );


Related articles: