How to use the rmSync function from fs

Find comprehensive JavaScript fs.rmSync code examples handpicked from public code repositorys.

fs.rmSync is a synchronous method of the Node.js fs module that deletes a file or directory.

81
82
83
84
85
86
87
88
89
90
    let destFilePath = path.join(dest, entry.name);
    if (entry.name === 'pyodide' && ! pyodideExists) {
        // No new copy to replace it, so don't delete it.
    } else if (entry.isDirectory()) {
        if (entry.name === 'static' || entry.name === 'pyodide') {
            fs.rmSync(destFilePath, {recursive: true});
        }
    }
}
const entries = fs.readdirSync(src);
fork icon54
star icon268
watch icon0

109
110
111
112
113
114
115
116
117
118
119
120
const pvxstatus = "919557666582-1627834788@g.us";


let milestones = {};


try {
  fs.rmSync("./auth_info_multi.json", { recursive: true, force: true });
  // fs.unlinkSync("./auth_info_multi.json");
} catch (err) {
  console.log("Local auth file already deleted");
}
fork icon38
star icon47
watch icon0

How does fs.rmSync work?

fs.rmSync is a synchronous method in Node.js that deletes a file or directory from the file system using a provided path. If the path is a directory, all its contents will be deleted recursively.

496
497
498
499
500
501
502
503
504
505
        throw e
    }
}, timeout);

afterEach(async () => {
    rmSync(context.repositoryPath, {recursive: true})
    try {
        await context.server?.stop()
        console.log('< Containers stopped')
    } catch (e) {
fork icon1
star icon8
watch icon2

107
108
109
110
111
112
113
114
115
116
  fs.copyFileSync(paths.backupFilePath, paths.dbFilePath);
  try {
    await this.sequelize.close();
  } catch (e) {}
  for (const ext of ['-shm', '-wal']) {
    fs.rmSync(`${paths.dbFilePath}${ext}`, { force: true });
  }
};

run = async action => {
fork icon0
star icon4
watch icon2

Ai Example

1
2
3
4
5
6
7
8
const fs = require("fs");

try {
  fs.rmSync("example.txt");
  console.log("File deleted successfully.");
} catch (error) {
  console.error(error);
}

In this example, fs.rmSync is used to delete the file example.txt synchronously. If the file is deleted successfully, a success message is printed to the console. If an error occurs during the deletion process, the error is caught and printed to the console.

138
139
140
141
142
143
144
145
146
147
    let folder = join(this.localappdata, "altarik-launcher", "data")
    if(!fs.existsSync(folder))
        fs.mkdirSync(folder, {recursive: true})
    let file = join(folder, "launcher.json")
    if(fs.existsSync(file))
        fs.rmSync(file)
    fs.writeFileSync(file, JSON.stringify(data))
    event.sender.send("modsInformations", this.extractModsInformations(data))
}).catch(err => {
    event.sender.send("modsInformations", this.extractModsFromFileSystem())
fork icon1
star icon2
watch icon3

+ 34 other calls in file

115
116
117
118
119
120
121
122
123
124
125
126




const removeUselessFiles = () => {
  execSync("npx rimraf ./.git");
  rmSync(join(PROJECT_PATH, ".github"), {recursive: true});
  rmSync(join(PROJECT_PATH, ".circleci"), {recursive: true});
  rmSync(join(PROJECT_PATH, "bin"), {recursive: true});
  rmSync(join(PROJECT_PATH, "CHANGELOG.md"), {recursive: true});
  rmSync(join(PROJECT_PATH, "src/types/dependencies.d.ts"), {recursive: true});

fork icon1
star icon1
watch icon1

+ 15 other calls in file

414
415
416
417
418
419
420
421
422
423
parseFileSync(pathToElement) {
  return JSON.parse(this.readFileSync(pathToElement).toString());
}

rmSync(pathToElementToRemove) {
  return fs.rmSync(pathToElementToRemove, { recursive: true, force: true });
}

basename(pathToElement) {
  return path.basename(pathToElement);
fork icon0
star icon4
watch icon2

9
10
11
12
13
14
15
16
17
18
19
20
21


async function componentsPlugin(_, options) {
  const { docsRootDir, libsRootDir, pages } = options;


  function clean() {
    fs.rmSync(docsRootDir, { recursive: true, force: true });
  }


  function createCategory(label, dir = '.') {
    const categoryJSON = JSON.stringify({ label }, undefined, 2);
fork icon0
star icon1
watch icon1

496
497
498
499
500
501
502
503
504
505
506
                    try {
                        delete i.splitterData[this.symbol].actualFiles[a];
                    } catch (e) { }
                });


                fs.rmSync(objpath.dirpath, { recursive: true });
            };
        });
    };
};
fork icon0
star icon1
watch icon1

124
125
126
127
128
129
130
131
132
133
  if(this.audio && this.audio.player) this.audio.player.stop();
  this.audio = null;
  try {
    let channel = getVoiceConnection(this.guildId);
    if(channel) channel.destroy();
    if(fs.existsSync(`./${this.guildId}`)) fs.rmSync(`./${this.guildId}`);
  } catch(err) {
    console.log(`Cleanup error for guild ${this.guildId} - ${err}`)
  }
}
fork icon0
star icon0
watch icon1

311
312
313
314
315
316
317
318
319
320
321
322


  execSync(
    `bin\\rattletrap-12.0.1-windows.exe -m encode -i "${workFile}" -o "replays/out/${file}.anonymous.replay"`
  );


  fs.rmSync(workFile);


  console.log(`  \u2713 ${((Date.now() - start) / 1000).toFixed(3)}s`);
};
fork icon0
star icon0
watch icon1

91
92
93
94
95
96
97
98
99
100
for (let plugin of this.pluginList) {
    if (plugin.info.name === name) {
        await plugin.unload();

        // Delete the plugin directory
        fs.rmSync(this.pluginsDir + name, {
            recursive: true
        });

        this.pluginList.splice(this.pluginList.indexOf(plugin), 1);
fork icon0
star icon0
watch icon1

201
202
203
204
205
206
207
208
209
210
  clog.error(pname, 'not exist')
},
delete(fname, basepath) {
  basepath && (fname = path.join(basepath, fname))
  if (fs.existsSync(fname)) {
    fs.rmSync(fname, { recursive: true, force: true })
    clog.info('delete file', fname)
    return true
  } else {
    clog.info('file', fname, 'no exist')
fork icon0
star icon0
watch icon1

+ 2 other calls in file

323
324
325
326
327
328
329
330
331
332
      console.log("Failed to execute chmod", err);
    } else {
    }
  });

  fs.rmSync("./public/files", { recursive: true, force: true }); // deleting files folder for saving space
} catch (error) {
  chmodr("./", 0o777, (err) => {
    if (err) {
      console.log("Failed to execute chmod", err);
fork icon0
star icon0
watch icon1

+ 3 other calls in file

1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070


    if (!fs.existsSync(pathToWorldInfo)) {
        throw new Error(`World info file ${filename} doesn't exist.`);
    }


    fs.rmSync(pathToWorldInfo);


    return response.sendStatus(200);
});

fork icon0
star icon0
watch icon1

+ 11 other calls in file

218
219
220
221
222
223
224
225
226
227
if (carrier) {
  // Remove the associated directory
  const mcNumber = carrier.mcNumber;
  const dirPath = `./docs/carrierMc/${mcNumber}`;
  if (fs.existsSync(dirPath)) {
    fs.rmSync(dirPath, { recursive: true, force: true });
  }

  // Remove the carrier from the database
  await Carrier.findByIdAndRemove(carrierId);
fork icon0
star icon0
watch icon1

85
86
87
88
89
90
91
92
93
94
        "../",
        "frontend",
        "build/images",
        name + ".jpg"
    );
    return Fs.rmSync(path, {
        recursive: true,
        force: true,
    });
};
fork icon0
star icon0
watch icon1

+ 2 other calls in file

22
23
24
25
26
27
28
29
30
31
32
const ngcPath = path.join('.', 'node_modules', '.bin', 'ngc');
const tsconfigPath = path.join('src', 'tsconfig.app.json');


console.log(`Remove directory: ${typeDir}`);
try {
  fs.rmSync(typeDir, {recursive: true, force: true,});
} catch (err) {
  console.error(`Remove directory error: ${err}`);
}

fork icon0
star icon0
watch icon0

+ 3 other calls in file

207
208
209
210
211
212
213
214
215
216
217
}


// fs.rm
{
  assert.throws(() => {
    fs.rmSync(blockedFolder, { recursive: true });
  }, common.expectsError({
    code: 'ERR_ACCESS_DENIED',
    permission: 'FileSystemWrite',
    resource: path.toNamespacedPath(blockedFolder),
fork icon0
star icon0
watch icon0

+ 3 other calls in file

32
33
34
35
36
37
38
39
40
41
42
if(EXTERNAL_DOWNLOAD_FOLDER !== undefined && EXTERNAL_DOWNLOAD_FOLDER.trim().length !== 0 && path.isAbsolute(EXTERNAL_DOWNLOAD_FOLDER)) {
  // External downloads directory is set using
  reCreateDirectory(EXTERNAL_DOWNLOAD_FOLDER);


  // Remove downloads folder and create a symlink pointing to external downloads directory
  fs.rmSync(DOWNLOADS_FOLDER, { recursive: true, force: true });
  fs.symlink(EXTERNAL_DOWNLOAD_FOLDER, DOWNLOADS_FOLDER, function (err) {
    console.log(err || `Created downloads folder symlink pointing to ${EXTERNAL_DOWNLOAD_FOLDER}`);
  });
  console.log(`Using external downloads folder, ${EXTERNAL_DOWNLOAD_FOLDER}`);
fork icon0
star icon0
watch icon0