Replace relative path to parent directory with dynamic root directory of a Node.js project
Search & Destory unnecessary relative requires in your unit tests
TLDR;
Prevent future directory changes from harshing your buzz in unit-tested node.js projects
The Command
LC_CTYPE=C find ./test/unit/ -type f -exec sed -i ".original" "s#'../../../../..#process.cwd() + '#g" {} \;
Unabridged Edition
We all love the elegance and simplicity of a "do only one thing and do it well" module.
Still many of our projects are large-scale customer-pleasers. While one of the joys of working on a large-scale project is seeing it evolve over time, that joy can turn to sorrow when you're constantly changing values to keep up with the changes.
It can be common in test code to refer to the module being tested by requiring it via a path above the test directory. I commonly see devs do this, even when process.cwd() (or an equivalent statement in another proglang) is sufficient. If this is the case in your project, you can do a quick search and destroy mission to rectify this situation, preventing any future project structure changes from taking up any of your precious time.
The Command (again)
LC_CTYPE=C find ./test/unit/ -type f -exec sed -i ".original" "s#'../../../../..#process.cwd() + '#g" {} \;
The Explanation
-
LC_TYPEPreventillegal byte sequencecomplaints on OS X -
findGet the list of files -
./test/unit/Replace this path with where you want to search -
sedDo your replacing -
".original"Make backups of the original versions of filessedmodifies -
#Use something other than'for delimiting in a regular expression -
gGlobal
Cleanup
You can remove the original files like so rm -rf test/unit/**/**/**/*.original