search
HomeWeb Front-endFront-end Q&ADeleting files from fs in nodejs

In Node.js, we can use the fs module to read and write files, which also includes file deletion operations. This article will introduce how to delete files using the fs module of Node.js.

fs module

In Node.js, the fs module is one of the most commonly used modules. It provides basic file operation functions, including file reading, Write, modify, delete and other operations. To use the fs module in Node.js, you first need to import the module:

const fs = require('fs');

fs.unlink()Method for deleting files. Its syntax is as follows:

fs.unlink(path, callback)

Among them, path represents the file path to be deleted, which can be an absolute path or a relative path; callback is the callback function after the deletion is completed. .

For example, delete the example.txt file in the current directory:

fs.unlink('example.txt', (err) => {
  if (err) throw err;
  console.log('文件已删除');
});

In the callback function, if an error occurs, an exception will be thrown, otherwise it will be output File deleted.

fs.unlinkSync()

In addition to using the callback function for asynchronous deletion operations, you can also use the fs.unlinkSync() method to perform synchronous deletion operations. How to use it Similar to the fs.unlink() method:

fs.unlinkSync(path);

For example, delete the example.txt file in the current directory:

fs.unlinkSync('example.txt');

But be careful Unfortunately, an exception will be thrown if an error occurs during the synchronous deletion operation, so error handling needs to be performed when calling this method.

Delete directory

Using fs.unlink() and fs.unlinkSync() methods can only delete files. If you want to delete a directory, You can use the fs.rmdir() or fs.rmdirSync() method, as shown below:

fs.rmdir(path, callback);
fs.rmdirSync(path);

where path means to delete The directory path can be an absolute path or a relative path.

It should be noted that when using fs.rmdir() to delete a directory, the directory must be an empty directory, otherwise the deletion will fail. If you want to delete a non-empty directory, you need to delete all files in the directory first, and then delete the directory.

Summary

This article introduces how to delete files using the fs module of Node.js, which are fs.unlink() and fs.unlinkSync(). To delete a directory, use the fs.rmdir() and fs.rmdirSync() methods. When using these methods to delete files, you need to ensure that the files are not used by other programs during the operation, otherwise the deletion will fail.

The above is the detailed content of Deleting files from fs in nodejs. For more information, please follow other related articles on the PHP Chinese website!

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
CSS: Can I use multiple IDs in the same DOM?CSS: Can I use multiple IDs in the same DOM?May 14, 2025 am 12:20 AM

No,youshouldn'tusemultipleIDsinthesameDOM.1)IDsmustbeuniqueperHTMLspecification,andusingduplicatescancauseinconsistentbrowserbehavior.2)Useclassesforstylingmultipleelements,attributeselectorsfortargetingbyattributes,anddescendantselectorsforstructure

The Aims of HTML5: Creating a More Powerful and Accessible WebThe Aims of HTML5: Creating a More Powerful and Accessible WebMay 14, 2025 am 12:18 AM

HTML5aimstoenhancewebcapabilities,makingitmoredynamic,interactive,andaccessible.1)Itsupportsmultimediaelementslikeand,eliminatingtheneedforplugins.2)Semanticelementsimproveaccessibilityandcodereadability.3)Featureslikeenablepowerful,responsivewebappl

Significant Goals of HTML5: Enhancing Web Development and User ExperienceSignificant Goals of HTML5: Enhancing Web Development and User ExperienceMay 14, 2025 am 12:18 AM

HTML5aimstoenhancewebdevelopmentanduserexperiencethroughsemanticstructure,multimediaintegration,andperformanceimprovements.1)Semanticelementslike,,,andimprovereadabilityandaccessibility.2)andtagsallowseamlessmultimediaembeddingwithoutplugins.3)Featur

HTML5: Is it secure?HTML5: Is it secure?May 14, 2025 am 12:15 AM

HTML5isnotinherentlyinsecure,butitsfeaturescanleadtosecurityrisksifmisusedorimproperlyimplemented.1)Usethesandboxattributeiniframestocontrolembeddedcontentandpreventvulnerabilitieslikeclickjacking.2)AvoidstoringsensitivedatainWebStorageduetoitsaccess

HTML5 goals in comparison with older HTML versionsHTML5 goals in comparison with older HTML versionsMay 14, 2025 am 12:14 AM

HTML5aimedtoenhancewebdevelopmentbyintroducingsemanticelements,nativemultimediasupport,improvedformelements,andofflinecapabilities,contrastingwiththelimitationsofHTML4andXHTML.1)Itintroducedsemantictagslike,,,improvingstructureandSEO.2)Nativeaudioand

CSS: Is it bad to use ID selector?CSS: Is it bad to use ID selector?May 13, 2025 am 12:14 AM

Using ID selectors is not inherently bad in CSS, but should be used with caution. 1) ID selector is suitable for unique elements or JavaScript hooks. 2) For general styles, class selectors should be used as they are more flexible and maintainable. By balancing the use of ID and class, a more robust and efficient CSS architecture can be implemented.

HTML5: Goals in 2024HTML5: Goals in 2024May 13, 2025 am 12:13 AM

HTML5'sgoalsin2024focusonrefinementandoptimization,notnewfeatures.1)Enhanceperformanceandefficiencythroughoptimizedrendering.2)Improveaccessibilitywithrefinedattributesandelements.3)Addresssecurityconcerns,particularlyXSS,withwiderCSPadoption.4)Ensur

What are the main areas where HTML5 tried to improve?What are the main areas where HTML5 tried to improve?May 13, 2025 am 12:12 AM

HTML5aimedtoimprovewebdevelopmentinfourkeyareas:1)Multimediasupport,2)Semanticstructure,3)Formcapabilities,and4)Offlineandstorageoptions.1)HTML5introducedandelements,simplifyingmediaembeddingandenhancinguserexperience.2)Newsemanticelementslikeandimpr

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools

Atom editor mac version download

Atom editor mac version download

The most popular open source editor

DVWA

DVWA

Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software