Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Copying file in node.js build script

Im playing around with a javascript project, it uses a node build script.

It syncing some folders into a built folder via

try {
  fs.statSync('built/imgs');
} catch(err) {
  if (err.code=='ENOENT') fs.symlinkSync('../imgs', 'built/imgs');
  else throw err;
}

Whats the corresponding fs command to get a real copy of the files to the built folder?

like image 821
Denny Mueller Avatar asked Apr 18 '13 18:04

Denny Mueller


People also ask

How do I copy and paste a file in node JS?

copyFile() method is used to asynchronously copy a file from the source path to destination path. By default, Node. js will overwrite the file if it already exists at the given destination. The optional mode parameter can be used to modify the behavior of the copy operation.

Which of the following will copy a file in node JS?

With Node. js 8.5, a new File System feature is shipped by which you can copy the files using the core fs module.

How do you copy and paste a file in JavaScript?

Copy() : File « MS JScript « JavaScript Tutorial. The Copy() method is used to copy a file. overwrite is a Boolean value indicating whether to overwrite an existing file of the same name. 32.9.


1 Answers

There is no function in the fs object that will copy a whole directory. There's not even one that will copy a whole file.

However, this is a quick and easy way to copy one file.

var fs = require('fs');

fs.createReadStream('input_filename').pipe(fs.createWriteStream('output_filename'));

Now you just need to get a directory list. You would use the fs.readdir or fs.readdirSync for that.

So to copy a directory to another you might do something like this:

var dir = fs.readdirSync('.');
for (var i=0; i < dir.length; i++) {
    fs.createReadStream(dir[i]).pipe(fs.createWriteStream("newpath/"+dir[i]));
}
like image 136
Daniel Avatar answered Oct 05 '22 12:10

Daniel