Web Front-end
JS Tutorial
This article will take you through the operation of reading and writing files in NodejsThis article will take you through the operation of reading and writing files in Nodejs
How to operate files in
Node? The following article will talk about how to use Nodejs to read and write files. I hope it will be helpful to you!

# Manipulating files is a basic function of the server and one of the necessary capabilities for back-end development.
Operating files mainly includes reading and writing. These functions Nodejs have already provided corresponding methods. Just call it.
Create folder
Synchronization method
const fs = require('fs')
fs.mkdirSync(`${__dirname}/雷猴`)
NodeJS There is a file module called fs . To operate on files, this module must be introduced first.
Use the fs.mkdirSync method to create a folder. Just enter the name of the folder to be created.
__dirname refers to the absolute path of the folder where the current file is located.
Asynchronous creation
const fs = require('fs')
fs.mkdir(`${__dirname}/雷猴`, err => {
if (err) {
console.error(err)
}
})
Use the fs.mkdir method to create asynchronously. The first parameter is also the folder name, and the second is Back to the function, there is a err parameter in this function, which can return error information.
Delete files
After creating the folder, I originally wanted to talk about "delete the folder". However, since all the files in the folder must be cleared before deleting it, the usage of Deleting files will be discussed first.
There are two ways to delete files: synchronous and asynchronous.
Synchronization fs.unlinkSync
const fs = require('fs')
fs.unlinkSync(`${__dirname}/test.txt`);
fs.unlinkSync Input the path and file name of the file to be deleted to delete the specified file.
Asynchronous fs.unlink
const fs = require('fs')
fs.unlink(`${__dirname}/test.txt`, err => {
if (err) {
console.error(err)
}
})
fs.unlink The method has 2 parameters. The first parameter is the file path and file name. The second parameter is the callback function that monitors deletion failure.
Delete Folder
Before deleting a folder, clear all files in the target folder. Files can be deleted using fs.unlinkSync or fs.unlink.
Sync
const fs = require('fs')
fs.rmdirSync(`${__dirname}/雷猴`)
Asynchronous
const fs = require('fs')
fs.rmdir(`${__dirname}/雷猴`, err => {
if (err) {
console.error(err)
}
})
The usage is similar to deleting files. There are also synchronous and asynchronous methods for deleting folders. , accepts 2 parameters asynchronously, and the second parameter is also a callback for monitoring error reports.
Write data
const fs = require('fs')
const content = ' 雷猴雷猴\n'
const opt = {
flag: 'a', // a:追加写入;w:覆盖写入
}
fs.writeFile('test.txt', content, opt, (err) => {
if (err) {
console.error(err)
}
})
fs.writeFile method can write content to a file. If the file does not exist, it will be automatically created.
fs.writeFile Parameter description:
- First parameter: file name
- Second parameter: written content
- The third parameter: writing mode (append, overwrite, etc.)
- The fourth parameter: error message monitoring
Reading data
const fs = require('fs')
fs.readFile('fileName', (err, data) => {
if (err) {
console.error(err)
return
}
// data 是二进制类型,需要转换成字符串
console.log(data.toString())
})
Use the fs.readFile method to read data. The first parameter is the file name; the second parameter is the callback, err monitors error messages, data is the data read back.
It should be noted that the data read back is a binary type of data, which needs to be converted into data we can understand using the toString() method.
Check whether the file exists
const fs = require('fs')
const exist = fs.existsSync('fileName')
console.log(exist)
Use the fs.existsSync method to check whether the specified file exists, and return true# if it exists. ## ; Otherwise, return false.
Summary
If you useNodeJS as the backend, you cannot escape the knowledge of reading and writing files. Its most common function can write logs, such as collecting error logs, etc.
nodejs tutorial!
The above is the detailed content of This article will take you through the operation of reading and writing files in Nodejs. For more information, please follow other related articles on the PHP Chinese website!
JavaScript and the Web: Core Functionality and Use CasesApr 18, 2025 am 12:19 AMThe main uses of JavaScript in web development include client interaction, form verification and asynchronous communication. 1) Dynamic content update and user interaction through DOM operations; 2) Client verification is carried out before the user submits data to improve the user experience; 3) Refreshless communication with the server is achieved through AJAX technology.
Understanding the JavaScript Engine: Implementation DetailsApr 17, 2025 am 12:05 AMUnderstanding how JavaScript engine works internally is important to developers because it helps write more efficient code and understand performance bottlenecks and optimization strategies. 1) The engine's workflow includes three stages: parsing, compiling and execution; 2) During the execution process, the engine will perform dynamic optimization, such as inline cache and hidden classes; 3) Best practices include avoiding global variables, optimizing loops, using const and lets, and avoiding excessive use of closures.
Python vs. JavaScript: The Learning Curve and Ease of UseApr 16, 2025 am 12:12 AMPython is more suitable for beginners, with a smooth learning curve and concise syntax; JavaScript is suitable for front-end development, with a steep learning curve and flexible syntax. 1. Python syntax is intuitive and suitable for data science and back-end development. 2. JavaScript is flexible and widely used in front-end and server-side programming.
Python vs. JavaScript: Community, Libraries, and ResourcesApr 15, 2025 am 12:16 AMPython and JavaScript have their own advantages and disadvantages in terms of community, libraries and resources. 1) The Python community is friendly and suitable for beginners, but the front-end development resources are not as rich as JavaScript. 2) Python is powerful in data science and machine learning libraries, while JavaScript is better in front-end development libraries and frameworks. 3) Both have rich learning resources, but Python is suitable for starting with official documents, while JavaScript is better with MDNWebDocs. The choice should be based on project needs and personal interests.
From C/C to JavaScript: How It All WorksApr 14, 2025 am 12:05 AMThe shift from C/C to JavaScript requires adapting to dynamic typing, garbage collection and asynchronous programming. 1) C/C is a statically typed language that requires manual memory management, while JavaScript is dynamically typed and garbage collection is automatically processed. 2) C/C needs to be compiled into machine code, while JavaScript is an interpreted language. 3) JavaScript introduces concepts such as closures, prototype chains and Promise, which enhances flexibility and asynchronous programming capabilities.
JavaScript Engines: Comparing ImplementationsApr 13, 2025 am 12:05 AMDifferent JavaScript engines have different effects when parsing and executing JavaScript code, because the implementation principles and optimization strategies of each engine differ. 1. Lexical analysis: convert source code into lexical unit. 2. Grammar analysis: Generate an abstract syntax tree. 3. Optimization and compilation: Generate machine code through the JIT compiler. 4. Execute: Run the machine code. V8 engine optimizes through instant compilation and hidden class, SpiderMonkey uses a type inference system, resulting in different performance performance on the same code.
Beyond the Browser: JavaScript in the Real WorldApr 12, 2025 am 12:06 AMJavaScript's applications in the real world include server-side programming, mobile application development and Internet of Things control: 1. Server-side programming is realized through Node.js, suitable for high concurrent request processing. 2. Mobile application development is carried out through ReactNative and supports cross-platform deployment. 3. Used for IoT device control through Johnny-Five library, suitable for hardware interaction.
Building a Multi-Tenant SaaS Application with Next.js (Backend Integration)Apr 11, 2025 am 08:23 AMI built a functional multi-tenant SaaS application (an EdTech app) with your everyday tech tool and you can do the same. First, what’s a multi-tenant SaaS application? Multi-tenant SaaS applications let you serve multiple customers from a sing


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

Safe Exam Browser
Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

WebStorm Mac version
Useful JavaScript development tools

SAP NetWeaver Server Adapter for Eclipse
Integrate Eclipse with SAP NetWeaver application server.

MinGW - Minimalist GNU for Windows
This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

Atom editor mac version download
The most popular open source editor






