How to delete a file in Node.js All In One

发布时间 2023-09-14 12:23:54作者: xgqfrms

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(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(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 ?
    if(fs.existsSync(file)) {
      fs.unlinkSync(file, err => {
        if (err) {
          console.log('File is deleted ❌')
          throw err
        } else {
          console.log('File is deleted ✅')
        }
      });
    }
    for (const group of this.groups) {
      // console.log(`group`, group)
      // console.log(`file`, file)
      if (!fs.existsSync(file)) {
        // create
        // console.log(`create`)
        const json = [group];
        // console.log(`json`, json)
        fs.writeFileSync(file, JSON.stringify(json, null, 4), (err) => {
          if(err) {
            console.log(`err ❌`)
          } else {
            console.log(`OK ✅`)
          }
        });
      } else {
        // append
        await this.appendFile(file, group);
      }
    }
    await this.downloadVideos();
  }

image

(? 反爬虫测试!打击盗版⚠️)如果你看到这个信息, 说明这是一篇剽窃的文章,请访问 https://www.cnblogs.com/xgqfrms/ 查看原创文章!

refs

https://attacomsian.com/blog/nodejs-delete-file



©xgqfrms 2012-2021

www.cnblogs.com/xgqfrms 发布文章使用:只允许注册用户才可以访问!

原创文章,版权所有©️xgqfrms, 禁止转载 ?️,侵权必究⚠️!