Deleting deeply nested node_modules

So, this is really one a quick one-off post of no real major technical achievement, I just had to do it today to get rid of some cruft left by Atom in my home directory, so I figured I’d share it. Mostly so the top post is a technical post, not some sentimental stuff from last year.

NodeJS, you love it, it’s everywhere. Sadly, they have a funky edge case that can occur on windows for really deeply nested dependencies that looks like this:

project/node_modules/dependency/node_modules/dependency/node_modules…

Windows file APIs have a big problem with file paths longer than the path limit (260 chars), it has trouble reading, writing or deleting them. So if we actually cared we would have to do something more involved, but since we want to delete them anyway, let’s just mangle the names.

function short_rename_children ($directory) {
  # 0-9, A-Z
  $name_chars = @(48..57) + @(65..90)
  $len = $name_chars.length

  function recurse {
    param($dir)

    pushd $dir
    $i = 0

    dir -Directory | % {
      $name = ''
      do {
        $name += [char] $name_chars[$i++ % $len]
      } while ([System.IO.Directory]::Exists($name))

      ren $_.Name $name
    }

    dir -Directory | % {
      recurse $_
    }

    popd
  }

  recurse $directory
}

Wait a while, because those directories can get deep, and then just rm -r -force the offending .atom directory or whatever it is you want to kill.

I think I’m gonna start documenting my side-project, so, hopefully more engaging content coming soon.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s