How to use the unlinkSync function from fs

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

fs.unlinkSync is a built-in Node.js function that removes the specified file synchronously from the file system.

204
205
206
207
208
209
210
211
212
213
 * @param  {string} file - file path
 * @return {undefined}
 */
exports.rm = function (file) {
    try {
        fs.unlinkSync(file);
    } catch (ex) {
        // ignore
    }
};
fork icon124
star icon815
watch icon42

+ 30 other calls in file

28
29
30
31
32
33
34
35
36
37
var COMMAND = exports.COMMAND;
class IpcServer {
    static start(tag) {
        let unixPath = util.format('/tmp/lightsword-%s.sock', tag);
        if (fs.existsSync(unixPath))
            fs.unlinkSync(unixPath);
        let server = net.createServer((client) => __awaiter(this, void 0, Promise, function* () {
            let data = yield client.readAsync();
            let msg = '';
            let mem;
fork icon71
star icon348
watch icon47

How does fs.unlinkSync work?

fs.unlinkSync is a synchronous method in the Node.js fs module that deletes a file from the file system, given the path of the file. When called, this method removes the file at the given path, and will throw an error if the file doesn't exist or if the user does not have permission to delete the file.

90
91
92
93
94
95
96
97
98
99
    return fs.writeFile(fileName, content, cb);
}

static remove(fileName) {
    try {
        fs.unlinkSync(fileName);
    } catch(e) {
        ;
    }
}
fork icon156
star icon0
watch icon0

+ 15 other calls in file

296
297
298
299
300
301
302
303
304
305
  const tempFilePath = `${tempDir}/${outputFileName}`;
  if (fs.existsSync(tempFilePath)) {
    fs.renameSync(tempFilePath, `${outputFileFolderWithoutSlash}/${outputFileName}`);
    fs.readdirSync(outputFileFolderWithoutSlash).forEach((foundFile) => {
      if (foundFile !== outputFileName) {
        fs.unlinkSync(`${outputFileFolderWithoutSlash}/${foundFile}`);
      }
    });
  }
},
fork icon51
star icon157
watch icon10

+ 12 other calls in file

Ai Example

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

try {
  fs.unlinkSync("file.txt");
  console.log("File deleted successfully");
} catch (err) {
  console.error(err);
}

This example attempts to delete a file named file.txt using the fs.unlinkSync method. If the file is successfully deleted, a success message is printed to the console. If there is an error in deleting the file, the error is caught and printed to the console instead.

110
111
112
113
114
115
116
117
118
119
120
121


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

88
89
90
91
92
93
94
95
96
97
exports.symlink = co.promisify(fs.symlink);
exports.symlinkSync = fs.symlinkSync;
exports.truncate = co.promisify(fs.truncate);
exports.truncateSync = fs.truncateSync;
exports.unlink = co.promisify(fs.unlink);
exports.unlinkSync = fs.unlinkSync;
exports.unwatchFile = fs.unwatchFile;
exports.utimes = co.promisify(fs.utimes);
exports.utimesSync = fs.utimesSync;
exports.watch = fs.watch;
fork icon22
star icon45
watch icon26

115
116
117
118
119
120
121
122
123
124
  const filename = []
  tmp.forEach(dirname => fs.readdirSync(dirname).forEach(file => filename.push(path.join(dirname, file))))
  filename.map(file => (
    stats = fs.statSync(file),
    stats.isFile() && (Date.now() - stats.mtimeMs >= 1000 * 60 * 3) ?
      fs.unlinkSync(file) :
      null))
}

async function connectionUpdate(update) {
fork icon92
star icon4
watch icon1

273
274
275
276
277
278
279
280
281
282
283
284
  };


  fs.unlink(nonexistentFile, common.mustCall(validateError));


  assert.throws(
    () => fs.unlinkSync(nonexistentFile),
    validateError
  );
}

fork icon42
star icon19
watch icon0

177
178
179
180
181
182
183
184
185
186
        const dirEnt = dir.readSync()
        if (dirEnt === null) {
            break;
        }
        if (dirEnt.isFile() && dirEnt.name.startsWith('zz_')) {
            fs.unlinkSync(dir.path + '/' + dirEnt.name);
        }
    }
    dir.close();
}
fork icon32
star icon57
watch icon0

+ 2 other calls in file

37
38
39
40
41
42
43
44
45
46

```js
const fs = require('fs');

try {
  fs.unlinkSync('/tmp/hello');
  console.log('successfully deleted /tmp/hello');
} catch (err) {
  // handle the error
}
fork icon209
star icon0
watch icon79

46
47
48
49
50
51
52
53
54
55
        'To change the Flow config, edit the template in ' +
        'scripts/flow/config/flowconfig. Then run this command again.\n',
    ),
  );
}
fs.unlinkSync(destPath);
fs.copyFileSync(srcPath, destPath);
// Set the mtime of the copied file to be same as the original file,
// so that the above check works.
fs.utimesSync(destPath, srcStat.atime, srcStat.mtime);
fork icon0
star icon1
watch icon0

23
24
25
26
27
28
29
30
31
32
async function main() {
    await mongoose.connect(mongodb);
}

try {
    fs.unlinkSync(`./${sessionName}.json`);
} catch (err) {
    console.log("Auth File Already Deleted");
}
const { state, saveState } = useSingleFileAuthState(`./${sessionName}.json`)
fork icon64
star icon3
watch icon0

65
66
67
68
69
70
71
72
73
74

it('fork should work', function(done) {
  const p = path.join(require('os').tmpdir(), 'yode-fork.js')
  fs.writeFileSync(p, "process.send('ok')")
  after(function() {
    fs.unlinkSync(p)
  })

  const child = require('child_process').fork(p)
  let sent = false
fork icon14
star icon126
watch icon5

+ 3 other calls in file

81
82
83
84
85
86
87
88
89
90
if (connection === 'close') {
    sessionMap.delete(parseInt(idevice))
    const logoutsessi = () => {
        chika.logout();
        if (fs.existsSync(`./app_node/session/device-${idevice}.json`)) {
            fs.unlinkSync(`./app_node/session/device-${idevice}.json`);
        }
    }
    let reason = new Boom(lastDisconnect?.error)?.output.statusCode
    if (reason === DisconnectReason.badSession) { console.log(`Bad Session File, Please Delete Session and Scan Again`); logoutsessi(); }
fork icon4
star icon2
watch icon0

+ 3 other calls in file

407
408
409
410
411
412
413
414
415
416
}

tryRemoveIcon(id) {
    try {
        const path = USERDATA_PATH + id +".svg";
        fs.unlinkSync(path);
        this.log("Icon removed: "+path);
    } catch(error) {
        this.log("Error removing device icon. Perhaps only driver icon was used. Error: "+error.message);
    }
fork icon6
star icon5
watch icon3

63
64
65
66
67
68
69
70
71
72
73
74
let connectRPCTimeout;
let updateChecker;


(async () => {
	const oldConfigFile = path.join(app.getPath('userData'), 'config.json');
	if (fs.existsSync(oldConfigFile)) fs.unlinkSync(oldConfigFile); // For security reasons we will delete the old config file as the new one will be encrypted, this one may contain sensitive information


	let encryptionKey = await keytar.getPassword(name, 'dpkey');
	if (!encryptionKey) {
		encryptionKey = crypto.randomBytes(32).toString('hex');
fork icon4
star icon28
watch icon1

275
276
277
278
279
280
281
282
283
284
    if (outputError.indexOf("skip_execution") == -1 && fs.existsSync(`/tmp/${device}-${manifest.fileName}.webp`)) {
        resolve(fs.readFileSync(`/tmp/${device}-${manifest.fileName}.webp`));
    } else {
        reject("Applet requested to skip execution...");
    }
    fs.unlinkSync(`/tmp/${device}-${manifest.fileName}.webp`);
} else {
    console.error(outputError);
    reject("Applet failed to render.");
}
fork icon2
star icon3
watch icon0

633
634
635
636
637
638
639
640
641
642
    penerimanyo.split("@")[0]
  } tunggu dia menyetujui undangan tersebut untuk chatan secara anonim jadi dia tidak tau siapa anda`,
  [penerimanyo]
);
let roomC = `#${makeid(10)}`;
fs.unlinkSync(PathAuto + sender.split("@")[0] + ".json");
var text_tersambung = `*Seseorang Mengajak Chating*\n\n*Dari:* Rahasia\n\nSilahkan klik button ya kak jika ingin menghubungkan chat *ANONYMOUS*`;
let btn_room = [
  {
    buttonId: `${prefix}buat_room_chat ${sender}|${data_pathauto.data.penerima}@s.whatsapp.net|${roomC}`,
fork icon2
star icon3
watch icon1

+ 33 other calls in file

82
83
84
85
86
87
88
89
90
91
92
93
  if (!isWindows)
    return fs.unlinkSync(path)


  const name = path + '.DELETE.' + crypto.randomBytes(16).toString('hex')
  fs.renameSync(path, name)
  fs.unlinkSync(name)
}


// this.gid, entry.gid, this.processUid
const uint32 = (a, b, c) =>
fork icon3
star icon2
watch icon0

1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
    if (!isAdmins) throw mess.admin
    if (!quoted) throw `Send/Reply Image With Caption ${prefix + command}`
    if (!/image/.test(mime)) throw `Send/Reply Image With Caption ${prefix + command}`
    if (/webp/.test(mime)) throw `Send/Reply Image With Caption ${prefix + command}`
    let media = await MoxieBotInc.downloadAndSaveMediaMessage(quoted)
    await MoxieBotInc.updateProfilePicture(m.chat, { url: media }).catch((err) => fs.unlinkSync(media))
    m.reply(mess.success)
    }
    break
case 'tagall': {
fork icon1
star icon1
watch icon2

+ 19 other calls in file