node. js Copy File

Source: Internet
Author: User

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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.