Skip to content

fs: add fs.copy, fs.copySync, fs.delete and fs.deleteSync with docs and tests.

So I and many other often need to recursively copy or delete directory's with node and copy file that keep their permissions and properties etc. Many use an external library or write their own and that takes up a lot of time and adds deps to your project which you might not want.

I have added fs.copy and fs.copySync to recursively copy directory's or just copy files, all files/directory's copied with fs.copy and fs.copySync retain they owners, mode and times.

fs.delete and fs.deleteSync either delete a file (basically an alias for fs.unlink) or of a directory is passed into the path recursively remove the content of the directory and remove the directory itself.

There are however a few notes, this is writen in JavaScript only and thus calls other functions in the fs module, I have placed the code at the bottom of lib/fs.js however there may be a better place to put the code.

I also change open the directory's for copying in different modes dependent on the platform, I use 'process.platform==="win32"?"r+":"r"' to determine the mode to open the directory in, I have done this because I found during testing that on Windows, you need to have the directory open in r+ mode to modify it's properties whereas on Linux it throws when you attempt to open a directory in r+ mode & you can open it in r mode and still change the properties. I don't have a Mac OS computer & thus cannot test it on Mac so this mode could be wrong on Mac.

I also use read streams and write streams in fs.copy however I use fs.readFileSync to read the file in fs.copySync, I know that this could load the entire file into the main memory and thus not be a great way of doing it however I am not sure how to do this better. So advise on this would be helpful.

I have also used readable.on('end') to determine when the copying of the file contents has ended, however I have seen the finish event used in some other cases, the end event seems to work to I haven't changed it but again that is something that might need changing.

My tests are relatively simplistic however they do test the copying. I haven't got a test for the overwrite mode being a function however I can write that if it is needed.

Hope this is OK, Jacob

Checklist
Affected core subsystem(s)

It changes the fs module, and adds docs.

Merge request reports

Loading