1. Node copy small files
Need to reference module require (' FS ');
Using Writefilesync and Readfilesync to copy small files, large files will drag down memory, not recommended.
Code
var fs = require (' FS ');
function CopyFile (src,dir)
{
Fs.writefilesync (Dir,fs.readfilesync (SRC));
}
CopyFile (' D:\\from\\config.json ', ' D:\\log\\dd.json ');
The path to the SRC source file. Dir to where the path is copied, and the file name behind it is the name of the file after the copy.
Note: dir must take the file name and file type, and when the test thought node would automatically use the name of the copied file, dir gave only one path, and it never succeeded.
2. Node uses file stream to copy files
var fs = require (' FS '),
Stat = Fs.stat;
var copy = function (_SRC, _DST) {
Read all files/directories in the directory
var readable, writable;
Stat (_SRC, function (err, ST) {
if (err) {
throw err;
}
Determine if the file is
if (St.isfile ()) {
Create read stream
readable = Fs.createreadstream (_SRC);
Create write Stream
writable = Fs.createwritestream (_DST);
To transport a stream through a pipeline
Readable.pipe (writable);
}
});
};
Copying a single file
Copy (' D:\\from\\config.json ', ' D:\\log\\dd.json ');
3. Copying a directory using file stream mode
var fs = require (' FS '),
Stat = Fs.stat;
/*
* Copy all files in the directory including sub-directories
* @param {String} directory to be copied
* @param {String} copied 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 if the file is
if (St.isfile ()) {
Create read stream
readable = Fs.createreadstream (_SRC);
Create write Stream
writable = Fs.createwritestream (_DST);
To transport a stream through a pipeline
Readable.pipe (writable);
}
Recursively calls itself if it is a directory
else if (st.isdirectory ()) {
Exists (_SRC, _DST, copy);
}
});
});
});
};
Before replicating the directory, you need to determine whether the directory exists, there is no need to first create the directory
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 Directory
Exists (' D:\\from ', ' d:\\log ', copy);
Node Copy file