kix8qq
Last Updated: February 25, 2016
·
1.898K
· jamesw

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_TYPE Prevent illegal byte sequence complaints on OS X
  • find Get the list of files
  • ./test/unit/ Replace this path with where you want to search
  • sed Do your replacing
  • ".original" Make backups of the original versions of files sed modifies
  • # Use something other than ' for delimiting in a regular expression
  • g Global

Cleanup

You can remove the original files like so rm -rf test/unit/**/**/**/*.original