Node copy directory example
This nodejs example post of mine will be on some javaScript code I put together for copying a directory. This might not be the best solution for all projects, but I am using some code to this effect in a project I am working on. There are many other node copy options out there on the web, many of which are packed with features that I will not use, I do not want, or I think should be pulled into another library. However in some respects they might also be a bit more robust compared to what I have worked out here.
1 - Log, copy, and mkdirp
before I get into the lib that is used to copy a directory I first want to go over the other files I have worked out for this node example. One of which is a way to define what logging is in place of using console.log, another is a lib that is used to copy just one file, and another is a rendition of mkdirp. All of these files will be used in the copy directory library that I will be going over in the next section.
1.1 - The log.js module
For this project I worked out a module that I am using for project wide logging. This allows for me to have better control over what is logged to the console. For example I can just comment out the code inside of the inner function, and that will make it so there is no logging at all for all modules. Another thing I can do is redefine what logging is, by using console.log rather than process.stdout.write, or logg to a file instead.
|
|
I know this is a little off topic, but it was something else I was doing for this project, as this is something I find myself coming back to now and then.
1.2 - The copy module
Now for the copy module, this module exports a single method that can be used to copy just a single file by going a source and target path.
|
|
1.3 - mkdirp
Another library that I am using for this project is an mkdirp lib. This is a function that will make sure that a folder path exists if it is not there to begin with.
|
|
2 - Copy dir
Now to get into the actually copy directory library now that I have covered the other files that it depends on. This library exports just one method called copyDir that takes a source path to a folder that is to be copied, and then a target path that the contents are to be copies too.
|
|
3 - Making a quick bin.js file
So now that I have all my libraries worked out it is time to see if what I worked out works as expected.
|
|
4 - Conclusion
So far this way of making a copy dir library seems to work okay at least, however there are some things that come to mind that are of concern. Mainly using streams rather than readFile, and writeFile in the copy.js file, and seeing about better error handing. There are thoughts that come to mind such as what will happen if I copy a folder that contains recursive symbolic links, I have not battle tested this after all. Still when it comes to the project that I am working on this seems to work okay for what I want it to do at least.