I am able to copy a file in node.js using the following:
var readStream = fs.createReadStream(fromFilePath);
readStream.pipe(fs.createWriteStream(toFilePath));
The question is how to also copy/keep the modified time (mtime) like in a regular file copy command.
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.
With Node. js 8.5, a new File System feature is shipped by which you can copy the files using the core fs module.
To overwrite a file using fs in Node. js, we can call writeFile or writeFileSync with the 'w' flag. to call writeFileSync with the file path , file content , and the 'w' flag to write the file even if it already exists. We can pass in the same arguments with writeFile to write the file asynchronously.
utimesSync() method is used to synchronously change the modification and access timestamps of a file. The timestamps can be specified using a number, string, or Date object.
Last Updated : 16 Aug, 2021 The fs.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.
How To Move & Copy Files In NodeJS – Simple Examples 1 To copy a file in NodeJS – require ("fs").copyFileSync ("SOURCE", "TARGET") 2 To move a file in NodeJS require ("fs").renameSync ("SOURCE", "TARGET") More ...
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. Parameters: This method accepts three parameters as mentioned above and described below:
Well, there are many use cases to this function. You might come across situations where you want to copy data from a file and maybe put it into use later in your code. However, copying a file in Node.js is not the same as reading a file and then writing its contents in another file.
There are methods in the fs
module to access mtime:
var stat = fs.statSync(fromFilePath);
fs.utimesSync(toFilePath, stat.atime, stat.mtime)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With