How to use the unlinkSync function from fs-extra

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

fs-extra.unlinkSync is a Node.js method that deletes a file synchronously from the file system.

509
510
511
512
513
514
515
516
517
    configString.indexOf('/' + imagePath) === -1 &&
    authorAvatars.indexOf(imagePath) === -1 &&
    imagePath !== ogFallbackImage
) {
    try {
        fs.unlinkSync(fullPath);
    } catch(e) {
        console.error(e);
    }
fork icon341
star icon0
watch icon79

+ 9 other calls in file

3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
        } else if (stat.isDirectory()) {
            // rmdir recursively
            this.rmdirCustom(filename);
        } else {
            // rm fiilename
            fs.unlinkSync(filename);
        }
    }
    fs.rmdirSync(dir);
};
fork icon80
star icon94
watch icon26

+ 17 other calls in file

How does fs-extra.unlinkSync work?

fs-extra.unlinkSync is a method provided by the fs-extra module in Node.js, which deletes a file from the file system synchronously, without any callbacks or promises involved. It takes a path to the file to be deleted as its only parameter.

102
103
104
105
106
107
108
109
110
111
} else {
   file_path = path.join(MASTER_CONFIG_PATH, domain, "user_" + owner, walkthrough + "_walkthrough.json");
}
// var walkthrough_file; // NOT USED
if (utils.fileExists(file_path)) {
   fs.unlinkSync(file_path);
   res.send({});
} else {
   res.status(404).send();
}
fork icon29
star icon68
watch icon15

+ 3 other calls in file

5793
5794
5795
5796
5797
5798
5799
5800
5801
5802
  fs.mkdirSync(destination_image_path, { recursive: true });
}

try {
  if (fs.existsSync(converted_image_file)) {
    fs.unlinkSync(converted_image_file);
  }
} catch (err) {
  conversion_success = false;
  console.error(err);
fork icon9
star icon22
watch icon9

+ 19 other calls in file

Ai Example

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

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

In this example, fs.unlinkSync is used to delete a file at /path/to/file.txt. If the file is successfully deleted, the message "File deleted successfully" will be logged to the console. If an error occurs during the deletion process, the error message will be logged to the console.

29
30
31
32
33
34
35
36
37
38
console.log("🔨 [debug] revokeUserKeys Revoked filenames: ", revoked_filenames);
for (var kindex in revoked_filenames) {
	if (!Util.isDefined(key_paths[kindex])) continue;
	var priv_path = this.ssh_keys + "/" + key_paths[kindex];
	var pub_path = this.ssh_keys + "/" + key_paths[kindex] + ".pub";
	if (fs.existsSync(priv_path)) fs.unlinkSync(priv_path);
	if (fs.existsSync(pub_path)) fs.unlinkSync(pub_path);
	revoked_keys.push(key_paths[kindex]);
}
return revoked_keys;
fork icon8
star icon20
watch icon0

+ 7 other calls in file

81
82
83
84
85
86
87
88
89
90
const dstDir = `${dataDir}/${dst}`
let hasFailures = false
const functions = config.rules.map((rule) => (done) => {
  OBAFilter(src, dst, rule).then((success) => {
    if (success) {
      fs.unlinkSync(`${dataDir}/${src}`)

      /* create zip named src from files in dst */
      zipDir(`${dataDir}/${src}`, `${dataDir}/${dst}`, () => {
        del([`${dataDir}/${dst}`])
fork icon21
star icon11
watch icon18

+ 4 other calls in file

100
101
102
103
104
105
106
107
108
      await Certificate.query().insert({ user_id, url: URL, register_at: Date.now().toString() });
    } catch (error) {
      return [errorHandler(error), null];
    }
    // delete pdf from assests
    fs.unlinkSync(filePath);
    return [null, URL];
  }
};
fork icon18
star icon15
watch icon4

+ 3 other calls in file

86
87
88
89
90
91
92
93
94
95
  const assessmentJson = `${courseFolderName}/${assessmentDetail.name}.json`;
  if (fs.existsSync(assessmentJson)) {
    const propertiesAssessmentJson = `${courseFolderName}/PARSED_CONTENT/PROPERTIES_FILES/${assessmentDetail.name}_en.json`;
    const modifiedAssessmentJson = `${courseFolderName}/PARSED_CONTENT/MODIFIED_FILES/${assessmentDetail.name}.json`;
    fs.unlinkSync(propertiesAssessmentJson);
    fs.unlinkSync(modifiedAssessmentJson);
    fs.unlinkSync(assessmentJson);
  }
}
await assessmentResult.query().delete().where('assessment_id', assessment_id);
fork icon18
star icon15
watch icon4

+ 23 other calls in file

122
123
124
125
126
127
128
129
130
131
132
133
    };
    this.__dirty = true;
};


PodsJson.prototype.destroy = function () {
    fs.unlinkSync(this.path);
    events.emit('verbose', util.format('Deleted `%s`', this.path));
};


PodsJson.prototype.write = function () {
fork icon2
star icon2
watch icon10

355
356
357
358
359
360
361
362
363

for (let fn of fList) {
    let fullFn = path.join(fullPath, fn);

    try {
        fs.unlinkSync(fullFn);
    } catch (e) {
        log.error('messages.action.delete_error', { "fileName": fullPath}, e);
    }
fork icon1
star icon5
watch icon4

+ 5 other calls in file

140
141
142
143
144
145
146
147
148
149
let unlinkCustomNodes = (details) => {
    console.log("unlinkCustomNodes");
    return new Promise((resolve, reject) => {
        details.nodeNames.forEach((node) => {
            try {
                fs.unlinkSync(path.join(details.userDir, "node_modules", node));
            } catch (err) {
                console.log(err);
                reject("Error : Unlinking Custom Node failed.", err);
            }
fork icon0
star icon2
watch icon0

7004
7005
7006
7007
7008
7009
7010
7011
7012
7013
const errorOnExist = options.errorOnExist
const preserveTimestamps = options.preserveTimestamps

if (fs.existsSync(destFile)) {
  if (overwrite) {
    fs.unlinkSync(destFile)
  } else if (errorOnExist) {
    throw new Error(`${destFile} already exists`)
  } else return
}
fork icon0
star icon1
watch icon0

+ 26 other calls in file

263
264
265
266
267
268
269
270
271
272
const gitignoreExists = fs.existsSync(path.join(appPath, '.gitignore'));
if (gitignoreExists) {
  // Append if there's already a `.gitignore` file there
  const data = fs.readFileSync(path.join(appPath, 'gitignore'));
  fs.appendFileSync(path.join(appPath, '.gitignore'), data);
  fs.unlinkSync(path.join(appPath, 'gitignore'));
} else {
  // Rename gitignore after the fact to prevent npm from renaming it to .npmignore
  // See: https://github.com/npm/npm/issues/1862
  fs.moveSync(
fork icon1
star icon0
watch icon2

+ 4 other calls in file

1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
if (app.licenseManager.getStatus() === true) {
  var buttonId =
    app.dialogs.showConfirmDialog('你想要删除现在的许可证密钥吗?')
  if (buttonId === 'ok') {
    var path = app.licenseManager.findLicense()
    fs.unlinkSync(path)
    app.licenseManager.checkLicenseValidity()
  }
  app.dialogs
} else {
fork icon0
star icon1
watch icon1

150
151
152
153
154
155
156
157
158
        let mime = citel.quoted.mtype
        let media = await Void.downloadAndSaveMediaMessage(citel.quoted);
        const { toAudio } = require('../lib')
        let audio = await toAudio(media, 'mp4')
        Void.sendMessage(citel.chat, { audio: audio, mimetype: 'audio/mpeg' }, { quoted: citel })
        await fs.unlinkSync(media)
        await fs.unlinkSync(audio)
    }
)
fork icon3
star icon0
watch icon1

+ 19 other calls in file

1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
            console.log(color('[FFmpeg]', 'green'), 'Processing finished!')
            await bocchi.sendMp4AsSticker(from, fileOutputPath, { fps: 30, startTime: '00:00:00.0', endTime : '00:00:05.0', loop: 0 })
            console.log(color('[WAPI]', 'green'), 'Success sending GIF!')
            setTimeout(() => {
                fs.unlinkSync(fileInputPath)
                fs.unlinkSync(fileOutputPath)
            }, 30000)
        })
        .save(fileOutputPath)
})
fork icon0
star icon0
watch icon1

+ 27 other calls in file

11
12
13
14
15
16
17
18
19
20
21
const Order = require('../../models/order');
const News = require('../../models/news');


function removeFile(path) {
    try {
        fs.unlinkSync(path);
    } catch (err) {
        console.error(err);
    }
}
fork icon0
star icon0
watch icon1

555
556
557
558
559
560
561
562
563
564
    }()

logger.loader(global.getText('mirai', 'finishLoadModule', global.client.commands.size, global.client.events.size))
logger.loader('=== ' + (Date.now() - global.client.timeStart) + 'ms ===')
writeFileSync(global.client['configPath'], JSON['stringify'](global.config, null, 4), 'utf8')
unlinkSync(global['client']['configPath'] + '.temp');

const listenerData = {};
listenerData.api = loginApiData;
listenerData.models = botModel;
fork icon0
star icon0
watch icon1

+ 5 other calls in file

15
16
17
18
19
20
21
22
23
24
if (fs.existsSync(path.join(global.dirPublic, "task.json"))) {
  let check = await Task();
  if (check?.slug != undefined) {
    return res.json({ status: false, msg: "server_busy" });
  } else {
    fs.unlinkSync(path.join(global.dirPublic, "task.json"));
  }
}

const sv_ip = await GetIP();
fork icon0
star icon0
watch icon1

+ 43 other calls in file

57
58
59
60
61
62
63
64
65
66
67
68
69
    
}


function deleteDB(user, databaseName){
    
    fs.unlinkSync(testFolder+user.name+"/Database/"+databaseName+".json")


}


function findUserById(userId){
fork icon0
star icon0
watch icon2

+ 4 other calls in file

function icon

fs-extra.readFileSync is the most popular function in fs-extra (9724 examples)