search
HomeWeb Front-endFront-end Q&AHow to use the fs method of nodejs

Node.js is a JavaScript running environment based on the Chrome V8 engine. It can run JavaScript code on the server side and handle high-concurrency, I/O-intensive applications. Node.js provides many built-in modules, including the file system module (fs). The fs module provides many methods for reading, writing, and manipulating files.

In this article, we will introduce the method of Node.js’s fs module. We'll explain what each method does and uses, and how to use them to process files.

  1. fs.open()

The fs.open() method is used to open files in Node.js. The syntax of this method is as follows:

fs.open(path, flags[, mode], callback)

Parameter description:

  • path: The path of the file to be opened.
  • flags: Flags for the operation to be performed. Optional parameter, default is 'w'.
  • mode: Set file mode (permissions and default interface). Optional parameter, default is 0666.
  • callback: callback function, parameters are (err, fd).

The flags parameter is a string indicating the operation mode. Some commonly used flags are listed below:

  • r: Open the file in read mode. If the file does not exist, an exception occurs.
  • r : Open the file in read and write mode. If the file does not exist, an exception occurs.
  • w: Open the file in writing mode. If the file does not exist, a new file is created. If the file exists, deletes all data contained in the file.
  • w : Open the file in read and write mode. If the file does not exist, a new file is created. If the file exists, deletes all data contained in the file.
  • a: Open the file in append mode. If the file does not exist, a new file is created.
  • a : Open the file in read and append mode. If the file does not exist, a new file is created.

Example:

const fs = require('fs');
fs.open('test.txt', 'w', function (err, fd) {
  if (err) {
    throw err;
  }
  console.log('文件已打开!');
});
  1. fs.readFile()

fs.readFile() method is used to read in Node.js document. The syntax of this method is as follows:

fs.readFile(path[, options], callback)

Parameter description:

  • path: The path of the file to be read.
  • options: Object or string specifying the encoding and flags of the file (default is 'utf8').
  • callback: callback function, parameters are (err, data).

Example:

const fs = require('fs');
fs.readFile('test.txt', function (err, data) {
  if (err) {
    throw err;
  }
  console.log(data.toString());
});
  1. fs.writeFile()

fs.writeFile() method is used to write in Node.js document. The syntax of this method is as follows:

fs.writeFile(file, data[, options], callback)

Parameter description:

  • file: The path of the file to be written.
  • data: The data to be written to the file.
  • options: Object or string specifying the encoding and flags of the file (default is 'utf8').
  • callback: callback function, parameter is (err).

Example:

const fs = require('fs');
fs.writeFile('test.txt', 'Hello Node.js!', function (err) {
  if (err) {
    throw err;
  }
  console.log('文件已保存!');
});
  1. fs.appendFile()

The fs.appendFile() method is used to append data in Node.js to file. The syntax of this method is as follows:

fs.appendFile(file, data[, options], callback)

Parameter description:

  • file: The path of the file to be written.
  • data: The data to be written to the file.
  • options: Object or string specifying the encoding and flags of the file (default is 'utf8').
  • callback: callback function, parameter is (err).

Example:

const fs = require('fs');
fs.appendFile('test.txt', 'Hello again!', function (err) {
  if (err) {
    throw err;
  }
  console.log('数据已追加到文件!');
});
  1. fs.unlink()

fs.unlink() method is used to delete files in Node.js . The syntax of this method is as follows:

fs.unlink(path, callback)

Parameter description:

  • path: The path of the file to be deleted.
  • callback: callback function, parameter is (err).

Example:

const fs = require('fs');
fs.unlink('test.txt', function (err) {
  if (err) {
    throw err;
  }
  console.log('文件已删除!');
});

6.fs.rename()

The fs.rename() method is used to rename files in Node.js. The syntax of this method is as follows:

fs.rename(oldPath, newPath, callback)

Parameter description:

  • oldPath: The old path of the file to be renamed.
  • newPath: The new path of the file to be renamed.
  • callback: callback function, parameter is (err).

Example:

const fs = require('fs');
fs.rename('test.txt', 'newTest.txt', function (err) {
  if (err) {
    throw err;
  }
  console.log('文件已重命名!');
});

Summary

In Node.js, the fs module provides many methods for reading, writing, and manipulating files. Use these methods to conveniently handle file system operations. This article introduces commonly used fs methods and provides practical examples. I hope this article can help you better understand the use of Node.js’s fs module.

The above is the detailed content of How to use the fs method of 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
What are the limitations of React?What are the limitations of React?May 02, 2025 am 12:26 AM

React'slimitationsinclude:1)asteeplearningcurveduetoitsvastecosystem,2)SEOchallengeswithclient-siderendering,3)potentialperformanceissuesinlargeapplications,4)complexstatemanagementasappsgrow,and5)theneedtokeepupwithitsrapidevolution.Thesefactorsshou

React's Learning Curve: Challenges for New DevelopersReact's Learning Curve: Challenges for New DevelopersMay 02, 2025 am 12:24 AM

Reactischallengingforbeginnersduetoitssteeplearningcurveandparadigmshifttocomponent-basedarchitecture.1)Startwithofficialdocumentationforasolidfoundation.2)UnderstandJSXandhowtoembedJavaScriptwithinit.3)Learntousefunctionalcomponentswithhooksforstate

Generating Stable and Unique Keys for Dynamic Lists in ReactGenerating Stable and Unique Keys for Dynamic Lists in ReactMay 02, 2025 am 12:22 AM

ThecorechallengeingeneratingstableanduniquekeysfordynamiclistsinReactisensuringconsistentidentifiersacrossre-rendersforefficientDOMupdates.1)Usenaturalkeyswhenpossible,astheyarereliableifuniqueandstable.2)Generatesynthetickeysbasedonmultipleattribute

JavaScript Fatigue: Staying Current with React and Its ToolsJavaScript Fatigue: Staying Current with React and Its ToolsMay 02, 2025 am 12:19 AM

JavaScriptfatigueinReactismanageablewithstrategieslikejust-in-timelearningandcuratedinformationsources.1)Learnwhatyouneedwhenyouneedit,focusingonprojectrelevance.2)FollowkeyblogsliketheofficialReactblogandengagewithcommunitieslikeReactifluxonDiscordt

Testing Components That Use the useState() HookTesting Components That Use the useState() HookMay 02, 2025 am 12:13 AM

TotestReactcomponentsusingtheuseStatehook,useJestandReactTestingLibrarytosimulateinteractionsandverifystatechangesintheUI.1)Renderthecomponentandcheckinitialstate.2)Simulateuserinteractionslikeclicksorformsubmissions.3)Verifytheupdatedstatereflectsin

Keys in React: A Deep Dive into Performance Optimization TechniquesKeys in React: A Deep Dive into Performance Optimization TechniquesMay 01, 2025 am 12:25 AM

KeysinReactarecrucialforoptimizingperformancebyaidinginefficientlistupdates.1)Usekeystoidentifyandtracklistelements.2)Avoidusingarrayindicesaskeystopreventperformanceissues.3)Choosestableidentifierslikeitem.idtomaintaincomponentstateandimproveperform

What are keys in React?What are keys in React?May 01, 2025 am 12:25 AM

Reactkeysareuniqueidentifiersusedwhenrenderingliststoimprovereconciliationefficiency.1)TheyhelpReacttrackchangesinlistitems,2)usingstableanduniqueidentifierslikeitemIDsisrecommended,3)avoidusingarrayindicesaskeystopreventissueswithreordering,and4)ens

The Importance of Unique Keys in React: Avoiding Common PitfallsThe Importance of Unique Keys in React: Avoiding Common PitfallsMay 01, 2025 am 12:19 AM

UniquekeysarecrucialinReactforoptimizingrenderingandmaintainingcomponentstateintegrity.1)Useanaturaluniqueidentifierfromyourdataifavailable.2)Ifnonaturalidentifierexists,generateauniquekeyusingalibrarylikeuuid.3)Avoidusingarrayindicesaskeys,especiall

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 Tools

SecLists

SecLists

SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

SublimeText3 English version

SublimeText3 English version

Recommended: Win version, supports code prompts!

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor