Wednesday, October 7, 2020
fnm on cd
Some time ago I have shown you how to run fnm use automatically
using direnv (here). That solution has
one problem however - you need to create .envrc file near each
.nvmrc.
As you already have .nvmrc wouldn’t it be nice if fnm use were
run when you enter your folder with .nvmrc in it. Doing it is
quite simple using bash:
function nvmrc_check() {
if [[ -f .nvmrc ]]
then
fnm use
fi
}
function cd() {
builtin cd "$@"
nvmrc_check
}
nvmrc_check
nvmrc_check function checks if there is .nvmrc file and runs
fnm use (feel free to use nvm if it is a weapon of your
choice). function cd() overrides cd command to run default
cd command and run nvmrc_check. In addition you need to run
nvmrc_check on start as your shell might start in the folder you
need.
This is solution has one problem however. If you cd to folder
that does not have .nvmrc (but for example parent folder has)
fnm use will not run. You can improve this script to check for
.nvmrc file back to parent and etc but I will leave this task
for you as exercise.