How to use the rm function from shelljs

Find comprehensive JavaScript shelljs.rm code examples handpicked from public code repositorys.

shelljs.rm is a Node.js module that allows you to delete files and directories from your file system.

13
14
15
16
17
18
19
20
21
22
// Sounds dangerous, but any files in root which share a name with src would have been overwritten by the build anyway.

srcContents.forEach(fileOrDir => {
  if (fileExists(`src/${fileOrDir}`) && fileExists(`./${fileOrDir}`)) {
    console.log(`deleting file ./${fileOrDir}`);
    sh.rm(`./${fileOrDir}`);
  } else if (dirExists(`src/${fileOrDir}`) && dirExists(fileOrDir)) {
    console.log(`deleting directory ./${fileOrDir}`);
    sh.rm('-rf', `./${fileOrDir}`);
  }
fork icon56
star icon535
watch icon20

+ 7 other calls in file

35
36
37
38
39
40
41
42
43
44

// when repo archive is unpacked the leading 'v' from tag is trimmed: v1.0.0.zip => sourcegraph-extensions-bundles-1.0.0
const bundlesRepoDirectoryName = `${bundlesRepoName}-${revision.replace(/^v/g, '')}`

// Remove existing repo and bundles directory in case of an interrupted process.
shelljs.rm('-rf', bundlesRepoDirectoryName)
shelljs.rm('-rf', pathToExtensionBundles)

// Unzip bundles repo archive, which creates a new directory: sourcegraph-extensions-bundles-{revision}
shelljs.exec(`unzip -q ${revision}.zip`)
fork icon936
star icon0
watch icon161

+ 3 other calls in file

How does shelljs.rm work?

shelljs.rm is a function provided by the ShellJS library that allows deleting files and directories using cross-platform compatible file paths and a variety of options. The function internally invokes the rm command provided by the operating system's shell to delete files and directories.

51
52
53
54
55
56
57
58
59

  await cloneFiles()

  shell.echo('\nCleaning files.')
  shell.cd(path.resolve(__dirname))
  shell.rm('-rf', cacheDir)

  shell.echo('\ndone.')
}
fork icon669
star icon0
watch icon88

631
632
633
634
635
636
637
638
639
640
spawnSync('npx', ['create-nuxt-app@latest', 'ui'], {
  stdio: 'inherit',
  shell: true,
});
if (fs.existsSync(path.join('ui', '.git'))) {
  sh.rm('-rf', path.join('ui', '.git')); // Remove NuxtJS' .git; we will init .git in our monorepo's root.
}
sh.mkdir(path.join('ui', 'middleware'));
sh.cp(
  path.join(__dirname, 'ui', 'nuxt', 'headers.js'),
fork icon29
star icon93
watch icon20

+ 44 other calls in file

Ai Example

1
2
3
4
const shell = require("shelljs");

// remove a file
shell.rm("file.txt");

20
21
22
23
24
25
26
27
28
29
30
gulp.task("azure-mvc-publish", azureMvcPublish);
gulp.task("aspmvc-build", aspmvcBuild);


gulp.task('deploy', function(done) {
    // remove clone folder
    shelljs.rm('-rf', './ej2aspmvc');
    var commitMessage = shelljs.exec('git log -1 --pretty=%B').stdout.trim();
    console.log('COMMIT MESSAGE: ' + commitMessage);
    // create clone directory
    fs.mkdirSync('./ej2aspmvc');
fork icon27
star icon9
watch icon13

+ 49 other calls in file

502
503
504
505
506
507
508
509
510
511
512
/**
 * Discover all examples and extract information from them.
 */
(async () => {
  shell.mkdir('-p', distPath);
  shell.rm('-rf', examplesRootPath);
  shell.cp('-r', sourceExamplesRootPath, examplesRootPath);


  const loadedGDevelop = await loadGDevelopCoreAndExtensions({
    gdevelopRootPath,
fork icon12
star icon26
watch icon4

178
179
180
181
182
183
184
185
186
187

// Move the xcodeproj and other name-based dirs over.
shell.mv(path.join(locations.xcodeCordovaProj, originalName + '-Info.plist'), path.join(locations.xcodeCordovaProj, name + '-Info.plist'));
shell.mv(path.join(locations.xcodeCordovaProj, originalName + '-Prefix.pch'), path.join(locations.xcodeCordovaProj, name + '-Prefix.pch'));
// CB-8914 remove userdata otherwise project is un-usable in xcode 
shell.rm('-rf',path.join(locations.xcodeProjDir,'xcuserdata/'));
shell.mv(locations.xcodeProjDir, path.join(locations.root, name + '.xcodeproj'));
shell.mv(locations.xcodeCordovaProj, path.join(locations.root, name));

// Update locations with new paths
fork icon9
star icon20
watch icon4

+ 37 other calls in file

223
224
225
226
227
228
229
230
231
232
        throw new Error("Expected coverage file to be generated, but it wasn't.");
    }
}

async function testRelease() {
    rm("-rf", join(workDir, "dist"));
    await execAsync("npm run release", workDir);

    if (
        !existsSync(
fork icon8
star icon5
watch icon8

+ 14 other calls in file

160
161
162
163
164
165
166
167
168
169
      await gen(core, fn);
      merger.add(fn);
    }
    await merger.save(p);
    for (let i = 0; i < pages; i++)
      shelljs.rm(p + '__' + i + '.' + core);
  }
  break;
case 'split-':
case 'split-index-':
fork icon7
star icon51
watch icon5

+ 50 other calls in file

103
104
105
106
107
108
109
110
111
112
beforeEach(() => {
    ({ Ec0lint } = require("../../../lib/ec0lint/ec0lint"));
});

after(() => {
    shell.rm("-r", fixtureDir);
});

describe("ec0lint constructor function", () => {
    it("the default value of 'options.cwd' should be the current working directory.", async () => {
fork icon5
star icon131
watch icon1

+ 69 other calls in file

209
210
211
212
213
214
215
216
217
218
shell.sed(/package [\w\.]*;/, 'package ' + pkg + ';', java_files[0]).to(destFile);
events.emit('verbose', 'Wrote out Android package name "' + pkg + '" to ' + destFile);

if (orig_pkg !== pkg) {
    // If package was name changed we need to remove old java with main activity
    shell.rm('-Rf',java_files[0]);
    // remove any empty directories
    var currentDir = path.dirname(java_files[0]);
    var sourcesRoot = path.resolve(locations.root, 'src');
    while(currentDir !== sourcesRoot) {
fork icon2
star icon0
watch icon0

234
235
236
237
238
239
240
241
242
243
244
245
}


// checks if file exists and then deletes. Error if doesn't exist
function removeFile (project_dir, src) {
    var file = path.resolve(project_dir, src);
    shell.rm('-Rf', file);
}


// deletes file/directory without checking
function removeFileF (file) {
fork icon2
star icon0
watch icon0

+ 3 other calls in file

125
126
127
128
129
130
131
132
133


    const json = JSON.stringify(versionsWithLatest.reverse(), null, 2);


    shell.exec(`echo '${json}' > ./pixi-versions.json`);
    // delete the file
    shell.rm('./scripts/pixiVersions.json');
})();
fork icon1
star icon6
watch icon4

+ 2 other calls in file

165
166
167
168
169
170
171
172
173
174
175
 * @param {String} options
 * @param {String} source
 * @returns {Void}
 */
function remove(options, source) {
    Shell.rm(options, source);
}


/**
 * Replaces the text with the given value in the given file
fork icon0
star icon3
watch icon0

308
309
310
311
312
313
314
315
316
317
// remove the default resource name from all drawable folders
function deleteDefaultResourceAt(baseDir, resourceName) {
    shell.ls(path.join(baseDir, 'res/drawable-*'))
    .forEach(function (drawableFolder) {
        var imagePath = path.join(drawableFolder, resourceName);
        shell.rm('-f', [imagePath, imagePath.replace(/\.png$/, '.9.png')]);
        events.emit('verbose', 'Deleted ' + imagePath);
    });
}

fork icon1
star icon2
watch icon1

+ 50 other calls in file

387
388
389
390
391
392
393
394
395
396
397
398
  return sh.mkdir('-p', ...dirs)
}


// Remove directory
extras.rmdir = function (...dirs) {
  return sh.rm('-rf', ...dirs)
}


// Rename file
extras.rename = function (from, to) {
fork icon0
star icon3
watch icon1

+ 56 other calls in file

58
59
60
61
62
63
64
65
66
67
    console.log("Deleting " + oldJar);
    shell.rm('-f', oldJar);
});
// Delete old library project if it existed.
if (shared) {
    shell.rm('-rf', nestedCordovaLibPath);
} else {
    // Delete only the src, since eclipse can't handle its .project file being deleted.
    shell.rm('-rf', path.join(nestedCordovaLibPath, 'src'));
}
fork icon0
star icon2
watch icon1

+ 39 other calls in file

252
253
254
255
256
257
258
259
260
261
core.info(`artifact repo url: ${artifact_repo_url}`)

const artifact_repo_path = path.resolve(process.cwd(), 'tmp', base)
core.info(`build repo path: ${artifact_repo_path}`)

const res_rm = shell.rm('-rf', artifact_repo_path)
core.info(`rm: ${res_rm.code}`)

const res_mkd = shell.mkdir('-p', artifact_repo_path)
core.info(`mkdir: ${res_mkd.code}`)
fork icon1
star icon1
watch icon24

+ 315 other calls in file

354
355
356
357
358
359
360
361
362
363
364
365
                self.getPlatformInfo().locations.www;


            self._removeModulesInfo(plugin, targetDir);
            // Remove stale plugin directory
            // TODO: this should be done by plugin files uninstaller
            shell.rm('-rf', path.resolve(self.root, 'Plugins', plugin.id));
        });
};


Api.prototype._getInstaller = function (type) {
fork icon0
star icon1
watch icon1

67
68
69
70
71
72
73
74
75
76
77
78
79


function buildRust() {
  shell.echo("BUILDING RUST...");


  // Cleanup the previous build, if it exists
  shell.rm("-rf", "./bin-package");
  shell.rm("-rf", "./build");


  // Cleanup any previous Rust builds, update deps, and compile
  shell.exec("npm ci --ignore-scripts");
fork icon0
star icon1
watch icon0

+ 3 other calls in file