Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Fastest way to copy a file in Node.js

The project that I am working on (Node.js) implies lots of operations with the file system (copying, reading, writing, etc.).

Which methods are the fastest?

like image 880
bonbonez Avatar asked Jul 02 '12 12:07

bonbonez


People also ask

How do I copy files from one node js file to another?

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 node js is faster?

The virtual machine can take the source code to compile it into the machine code at runtime. What it means is that all the “hot” functions that get called often than not can be compiled to the machine code thus boosting the execution speed.


1 Answers

Use the standard built-in way fs.copyFile:

const fs = require('fs');  // File destination.txt will be created or overwritten by default. fs.copyFile('source.txt', 'destination.txt', (err) => {   if (err) throw err;   console.log('source.txt was copied to destination.txt'); }); 

If you have to support old end-of-life versions of Node.js - here is how you do it in versions that do not support fs.copyFile:

const fs = require('fs'); fs.createReadStream('test.log').pipe(fs.createWriteStream('newLog.log')); 
like image 83
Miguel Sanchez Gonzalez Avatar answered Sep 16 '22 11:09

Miguel Sanchez Gonzalez