How to delete a file in Node.js All In One
delete / remove
fs.unlinkSync
fs.unlinkSync(path)
path <string> | <Buffer> | <URL>
Synchronous (unlink(2) . Returns undefined.
fs.unlink
fs.unlink(path, callback)
path <string> | <Buffer> | <URL>
callback <Function>
err <Error>
Asynchronously
removes a file or symbolic link. No arguments other than a possible exception are given to the completion callback.
fs.unlink()
will not work on a directory
, empty or otherwise. To remove a directory, usefs.rmdir()
.
See the POSIX unlink(2) documentation for more details.
import { unlink } from 'node:fs';
// Assuming that 'path/file.txt' is a regular file.
unlink('path/file.txt', (err) => {
if (err) throw err;
console.log('path/file.txt was deleted');
});
https://nodejs.org/api/fs.html#fsunlinkpath-callback
fsPromises.unlink
fsPromises.unlink(path)
Added in: v10.0.0
path <string> | <Buffer> | <URL>
Returns: <Promise>
Fulfills with undefined upon success.
If path refers to a symbolic link
, then the link is removed without affecting the file or directory to which that link refers.
If the path refers to a file path that is not a symbolic link, the file is deleted.
See the POSIX unlink(2) documentation for more detail
https://nodejs.org/api/fs.html#fspromisesunlinkpath
Promise
unlink
// ESM
import { unlink } from 'node:fs/promises';
try {
await unlink('/tmp/hello');
console.log('successfully deleted /tmp/hello');
} catch (error) {
console.error('there was an error:', error.message);
}
// CJS
const { unlink } = require('node:fs/promises');
(async function(path) {
try {
await unlink(path);
console.log(`successfully deleted ${path}`);
} catch (error) {
console.error('there was an error:', error.message);
}
})('/tmp/hello');
https://nodejs.org/api/fs.html#promise-example
Callback
unlink
//ESM
import { unlink } from 'node:fs';
unlink('/tmp/hello', (err) => {
if (err) throw err;
console.log('successfully deleted /tmp/hello');
});
// CJS
const { unlink } = require('node:fs');
unlink('/tmp/hello', (err) => {
if (err) throw err;
console.log('successfully deleted /tmp/hello');
});
Synchronous
unlinkSync
The synchronous
APIs block the Node.js event loop and further JavaScript execution until the operation is complete.
Exceptions are thrown immediately and can be handled using try…catch
, or can be allowed to bubble up
.
// ESM
import { unlinkSync } from 'node:fs';
try {
unlinkSync('/tmp/hello');
console.log('successfully deleted /tmp/hello');
} catch (err) {
// handle the error
}
// CJS
const { unlinkSync } = require('node:fs');
try {
unlinkSync('/tmp/hello');
console.log('successfully deleted /tmp/hello');
} catch (err) {
// handle the error
}
demos
fs.unlinkSync
async writeJSONFile() {
const file = path.join(__dirname + `/videos.json`);
// clear & delete a file
标签:Node,fs,console,err,js,How,file,path,unlink
From: https://www.cnblogs.com/xgqfrms/p/17702213.html