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 to implement it. You can use readFile and writeFile directly to copy a single file, which is easier. If you copy all files in a directory, and the directory may also contain subdirectories, then you need to use a more advanced API.
flow
Streams are the way Node.js move data. Streams in Node.js are readable/writable, and both HTTP and file system modules use streams. In the file system, when using streams to read files, a large file may not be read at once, but will be read several times. When reading, it will respond to data events. You can operate on the read data before the file is read. Similarly, when writing to a stream, large files are not written at one time, just like when reading. This way of moving data is very efficient, especially for large files. Using streams is much faster than waiting for all large files to be read before operating the files.
pipeline
If you want to have complete control when reading and writing streams, you can use data events. But for simple file replication, read streams and write streams can transfer data through pipelines.
Practical application:
The code copy is as follows:
var fs = require( 'fs' ),
stat = fs.stat;
/*
* Copy all files in the directory including subdirectories
* @param{ String } Directory that needs 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 it is a file
if( st.isFile() ){
// Create a read stream
readable = fs.createReadStream( _src );
// Create a write stream
writable = fs.createWriteStream( _dst );
// Transfer streams through pipelines
readable.pipe( writable );
}
// If it is a directory, call itself recursively
else if( st.isDirectory() ){
exists( _src, _dst, copy );
}
});
});
});
};
// Before copying the directory, you need to determine whether the directory exists. If it does not exist, you need to 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 );