Using rimraf npm package to delete node_modules folder on Windows

When you try to delete the node_modules folder on Windows, you may see an error that says the source path is too long.

Here’s a screenshot of the error:

This error happens because Windows can’t delete a file that has a path longer than 260 characters.

When you install dependencies using the npm install command, many of the packages your project used will also have their own dependencies.

Installing all the dependencies will create deep-nested folders, resulting in a long path as follows:

node_modules\gulp-connect\
node_modules\gulp-util\
node_modules\dateformat\
node_modules\meow\
node_modules\normalize-package-data\
node_modules\validate-npm-package-license\
node_modules\spdx-expression-parse\
node_modules\spdx-license-ids\spdx-license-ids.json

In the above example, the gulp-connect module has a dependency on the gulp-util module, which depends on the dateformat module, which depends on meow module, and so on.

This is what causes Windows unable to delete your node_modules folder.

The same error shows up when you use the rmdir command from the command line:

$ rmdir node_modules /S
node_modules\gulp-connect\
node_modules\gulp-util\
node_modules\dateformat\
node_modules\meow\
node_modules\normalize-package-data\
node_modules\validate-npm-package-license\
node_modules\spdx-expression-parse\
node_modules\spdx-license-ids\spdx-license-ids.json - The file name is too long.

To easiest way to delete the node_modules folder is to use the rimraf package from npm.

rimraf is a utility module that allows you to perform a recursive removal of files and folders.

It’s like using the rm -rf command in UNIX-based operating systems.

You can install rimraf on Windows with npm:

npm install -g rimraf

Then use it to delete your node_modules folder from the command line:

rimraf node_modules

Alternatively, you can also use rimraf with npx so you don’t need to globally install it:

npx rimraf node_modules

rimraf is a nice utility package that helps you delete files on your computer.

It will work on a Windows machine even when the file path is longer than 260 characters.

Take your skills to the next level ⚡️

I'm sending out an occasional email with the latest tutorials on programming, web development, and statistics. Drop your email in the box below and I'll send new stuff straight into your inbox!

No spam. Unsubscribe anytime.