node. JS provides an API for file operations, but does not have a direct copy of the file's associated operations. However, you can use the FS module to write a simple copy file program.
varFS = require (' FS ');functionCopy (FILENAME,SRC) {fs.writefilesync (filename, fs.readfilesync (src)); //filename If it does not exist, a new file is created on the path}functionMain (argv) {copy (argv[0], argv[1]);//Argv[0] is the name of the file to be copied, argv[1] is the source of the copied data}fs.stat (Process.argv.slice (2) [1],function(err, stats) {//Check whether the file if(Stats.isfile ()) {main (Process.argv.slice (2)); }Else{Console.log (' Invalid file '); }});
The above procedure obtains the file information through the stats class, Isfile determines whether is the file, then through Fs.writefilesync,Fs.readfilesync synchronously writes or reads the file.
PROCESS.ARGV get command line arguments. However, Argv[0],argv[1] is the absolute path of the Nodejs execution program and the absolute path of the running module, so argv[2] is the input parameter and can be intercepted by slice ().
However, this way is to read all the contents of the file first to memory and then write to the specified path all at once, if the file is large, memory can not bear, so the copy of the large file may be implemented in the way of data flow, the original program copy function modified
function Copy (filename,src) { fs.createreadstream (src). Pipe (Fs.createwritestream (filename));}
Fs.createreadstream creates a read-only data stream,Fs.createwritestream creates a write-only stream, and the pipe () connects two data streams together for transmission.
When reading a file through a data stream, a large file is read multiple times, even if the file is not finished reading, it can manipulate the read data, write to the file is the same, in this way to copy the data is very efficient.
File Operations Related api:http://nodejs.cn/api/fs.html
node. js Copy File