首页 > 编程语言 >How to delete a file in Node.js All In One

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

时间:2023-09-14 12:45:27浏览次数:39  
标签:Node fs console err js How file path unlink

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 

标签:Node,fs,console,err,js,How,file,path,unlink
From: https://www.cnblogs.com/xgqfrms/p/17702213.html

相关文章

  • js简单的倒计时器~~⏰
    1.效果图2.html部分3.逻辑部分3.1获取当前时间,时间差//获取当前时间vardate=newDate();varnow=date.getTime();//设置截止时间varstr="2023/9/1412:28:34";varendDate=newDate(str);varend=......
  • netcore请求json斜杠带空格导致请求报错
    我用netcore发布了一个webapi接口,个别电脑,同样的浏览器(谷歌),swagger调用接口的时候,它的json体会加空格,然后请求就会报错。这是控制器里的方法下图是请求输入: 下图是加了空格的请求内容,如红色框所示,带了空格 下图是报错的内容下图是正常请求的内容,可以返回想要的结果......
  • How to fix java.net.SocketException: Too many files open in tomcat
    NotmanyJavaprogrammersknowsthatsocketconnectionsaretreatedlikefilesandtheyusefiledescriptor,whichisalimitedresource.Differentoperatingsystemhasdifferentlimitsonnumberoffilehandlestheycanmanage.Oneof......
  • How to change the default keep-alive time-out value in Internet Explorer
    [b]SUMMARY:[/b]ThisarticledescribeshowtochangethedefaultHTTPkeep-alivevalueinMicrosoftInternetExplorer.WhenInternetExplorerestablishesapersistentHTTPconnectionwithaWebserver(byusingConnection:Keep-Alive......
  • java/jsp清除jsp缓存
    InJava:HttpServletResponseresponse=(HttpServletResponse)rep;response.setDateHeader("Expires",-1);response.setHeader("Cache_Control","no-cache");response.setHeader("Pragma","no-ca......
  • JSP两种注释方法
    用了这么久的jsp和java,还不是很清楚jsp页面的注释。^-^1.[b]第一种用显式注释:<!--comment-->[/b]forexample:<!--<geh:checkLogon/>-->此种注释还是会让JVM编译、解释和执行。2.[b]第二种用隐式注释:<%--comment--%>[/b]forexample:<%--......
  • How to fix Tailwind CSS colors not work in Next.js All In One
    HowtofixTailwindCSScolorsnotworkinNext.jsAllInOneTailwindCSS&Next.js13errorimporttype{Config}from'tailwindcss'constconfig:Config={content:['./src/pages/**/*.{js,ts,jsx,tsx,mdx}','......
  • JS深入学习笔记 - 第二章.类和对象
    3.类和对象3.1面向对象这里顺带提一句学习JAVA时,老师说的面向对象和面向过程的区别:面向过程:强调做什么事情,具体什么步骤。举个把大象放进冰箱的例子:打开冰箱门把大象放进冰箱关上冰箱门面向对象:强调的是做动作的主体(称之为对象)冰箱:打开操作冰箱:放的操作(放的可以是大象......
  • js中使用0 “” null undefined {}需要注意 if判断时候都是false,比如判断接收后台数
    js中使用0“”nullundefined{}需要注意if判断时候都是false,比如判断接收后台数据if(data.info){}注意:在js中0为空(false),代表空的还有“”,null,undefined;如果做判断if(!上面的四种值);返回均为false?1234567console.log(!null);//trueconsole.log(!0);//trueconsole.lo......
  • 关于 Angular 应用里 Rxjs filter 操作符内的双重感叹号的用法
    看下列这段出现在AngularComponent内的代码:protecteduserCostCenters$:Observable<CostCenter[]>=this.userCostCenterService.getActiveCostCenters().pipe(filter((costCenters)=>!!costCenters));这段Angular组件代码涉及到Observable和RxJS操作......