This article mainly introduces. js Implementation of file replication methods and instances, using the FS module, friends can refer to the next Node. js does not provide APIs for directly copying files. If you want to use Node. js to copy files or directories, you need to use other APIs. To copy a single file, you can directly use readFile and writeFile, which is easier. If you are copying all the files in a directory and the directory may contain subdirectories, you need to use more advanced APIs.
Stream
Stream is the way Node. js moves data. The stream in Node. js is readable/writable. Both HTTP and file system modules are useful to the stream. In a file system, when a stream is used to read a file, a large file may not be read at once, but will be read several times, and the data event will be returned during the read, you can operate on the read data when the file is not read. Similarly, when writing a stream, it is the same as when reading it. Large files are not written at a time. This method of moving data is very efficient, especially for large files, using a stream is much faster than waiting to read all the large files.
MPs queue
If you want to fully control reading and writing streams, you can use data events. However, for file replication alone, data can be transmitted through pipelines to read and write streams.
Practical application:
The Code is as follows:
Var fs = require ('fs '),
Stat = fs. stat;
/*
* Copy all files in the directory, including subdirectories.
* @ Param {String} directory to be copied
* @ Param {String} copy to the specified directory
*/
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 whether the object is a file
If (st. isFile ()){
// Create a read stream
Readable = fs. createReadStream (_ src );
// Create a write stream
Writable = fs. createWriteStream (_ dst );
// Transmit streams through pipelines
Readable. pipe (writable );
}
// Recursively call itself if it is a directory
Else if (st. isDirectory ()){
Exists (_ src, _ dst, copy );
}
});
});
});
};
// Determine whether the directory exists before copying the directory. If the directory does not exist, create a directory first.
Var exists = function (src, dst, callback ){
Fs. exists (dst, function (exists ){
// Already exists
If (exists ){
Callback (src, dst );
}
// Does not exist
Else {
Fs. mkdir (dst, function (){
Callback (src, dst );
});
}
});
};
// Copy the Directory
Exists ('./src','./build ', copy );