search
HomeWeb Front-endJS TutorialLet's talk about how to use node to write and read file content

nodeHow to perform read and write operations? The following article will introduce you to the basic method of writing and reading file content using node.js. I hope it will be helpful to you!

Let's talk about how to use node to write and read file content

Node.js is a JavaScript running environment based on the Chrome V8 engine. [Related tutorial recommendations: nodejs video tutorial, Programming teaching

Lets talk about how to use node to write and read file content

Differentiation version number

LTS is a long-term stable version. It is recommended to install the LTS version of Node.js. Current is an early adopter version of new features, for students who are keen to try new features. It is recommended to install the Current version of Node.js.

Read file content

Use readFile to read file content

Failure to read is an error object

If successful, it is undefined

// 1.导入fs模块,操作文件
const fs = require('fs');
// 2.调用readFile() 方法 来读取文件
// 第一个参数是被读取文件的路径
// 第二个参数是编码格式
// 第三个参数是回调函数,拿到读取成功(dataStr)或者是失败的结果 (err)
fs.readFile('./file/01.text', 'utf8', function (err, dataStr) {
    console.log(err);// 打印失败的结果
    console.log("---------------------");
    console.log(dataStr);// 打印成功的结果
})

Lets talk about how to use node to write and read file content

Determine whether the file is read successfully

const fs = require('fs');

fs.readFile('./file/01.txt', 'utf8', function (err, dataStr) {
    if (err) {
        return console.log('读取失败!' + err.message);
    }
    console.log('读取成功!' + dataStr);
})

Success

Lets talk about how to use node to write and read file content

Failed

Lets talk about how to use node to write and read file content

Use writeFile to write the file content

const fs = require('fs');
// 三个参数
// 参数1表示文件存放路径
// 参数2表示要写入文件的内容
// 参数3回调函数
fs.writeFile('./file/02.text', 'Aic大山鱼', function (err) {
    // 写入成功后err的值就是null,且在该文件夹下生成一个02文件 
    if (err) {
        return console.log('文件写入失败!' + err.message);
    }
    console.log('文件写入成功!');
})

Lets talk about how to use node to write and read file content

Organizing data

Thinking sorting

Requirements: Organize the contents of one file and put them in another file. Separate the name and score with colons

1. Import the required fs file system module

2. Use the fs.readFile0 method to read the report-card.txt file in the material directory

3. Determine whether the file is read Failed to retrieve

4. After successfully reading the file, process the score data

5. Call the fs.writeFile0 method to write the processed score data to the new file report-card(1 ).txt

// 导入fs模块
const fs = require('fs');
// 调用resdFile()方法 读取文件
fs.readFile('./file/report-card.txt', 'utf8', function (err, dataStr) {
    toString(dataStr);
    // 判断是否读取成功
    if (err) {
        return console.log('读取失败!' + err.message);
    }
    // 把获取到的成绩用逗号分隔开保存
    const arrOld = dataStr.split(',');
    // 循环分割后的每一个数组,进行字符串的替换操作
    const arrNew = [];
    // item代表要遍历那个数组里的每一项
    arrOld.forEach(item => {
        // 把=替换成:
        arrNew.push(item.replace('=', ':'))
    });
    // 把新数组的每一项进行合并得到新的字符串
    const newStr = arrNew.join('\n');
    // 使用writeFile()方法,把处理完毕的数据写入到新文件中
    fs.writeFile('./file/report-card(1).txt', newStr, function (err) {
        if (err) {
            return console.log('写入失败!' + err.message);
        }
        console.log('写入成功!');
    })
})

Path dynamic splicing processing problem

When using the fs module to operate files, if the provided operation path is relative starting with / or ./ When using paths, it is easy to have path dynamic splicing errors.

Reason: When the code is running, the full path of the operated file will be dynamically spliced ​​from the directory where the node command is executed.

// __dirname 表示当前文件所处的目录
const fs = require('fs');
// 使用方法
fs.readFile(__dirname + '/file/01.txt', 'utf8', function (err, dataStr) {
    if (err) {
        return console.log('读取失败!' + err.messages);
    }
    console.log('读取成功!' + dataStr);
})

The path module is a module officially provided by Node.js for processing paths. It provides a series of methods and properties to meet users' needs for path processing.

●path.join() method, used to splice multiple path fragments into a complete path string

●path.basename() method, used to extract from a path string , parse the file name out

const path = require('path');
// ../会抵消一层路径
const pathStr = path.join('/a', '/v', '../', '/d', 'c');
console.log(pathStr);
const path = require('path');
const fs = require('fs');
fs.readFile(path.join(__dirname, +'/file/01.txt'), 'utf8', function (err, dataStr
) {
    if (err) {
        return console.log(err.message);
    }
    console.log(dataStr);
})

path.basename uses

const path = require('path');
const fpath = '/a/d/c/index.html'
const fullName = path.basename(fpath);
console.log(fullName);
// 移除后缀名
const nameWithoutExt = path.basename(fpath, '.html');
console.log(nameWithoutExt);

to get the file extension in the path

path.extname() method

const path = require('paht');
const fpath = '/a/s/d/f/index.html'// 路径字符串
const fext = path.extname('fpath');
console.log(fext);// 输出.html

Write at the end

I am Aic Shanyu , thank you for your support
It is not easy to be original ✨ I also hope to support
Like?: Your appreciation is the motivation for me to move forward!
Collection⭐: Your support is the source of my creation!
Comment ✍: Your suggestions are the best medicine for my improvement!
Shanyu Community: Shanyu Community ??

For more node-related knowledge, please visit: nodejs tutorial!

The above is the detailed content of Let's talk about how to use node to write and read file content. For more information, please follow other related articles on the PHP Chinese website!

Statement
This article is reproduced at:csdn. If there is any infringement, please contact admin@php.cn delete
Javascript Data Types : Is there any difference between Browser and NodeJs?Javascript Data Types : Is there any difference between Browser and NodeJs?May 14, 2025 am 12:15 AM

JavaScript core data types are consistent in browsers and Node.js, but are handled differently from the extra types. 1) The global object is window in the browser and global in Node.js. 2) Node.js' unique Buffer object, used to process binary data. 3) There are also differences in performance and time processing, and the code needs to be adjusted according to the environment.

JavaScript Comments: A Guide to Using // and /* */JavaScript Comments: A Guide to Using // and /* */May 13, 2025 pm 03:49 PM

JavaScriptusestwotypesofcomments:single-line(//)andmulti-line(//).1)Use//forquicknotesorsingle-lineexplanations.2)Use//forlongerexplanationsorcommentingoutblocksofcode.Commentsshouldexplainthe'why',notthe'what',andbeplacedabovetherelevantcodeforclari

Python vs. JavaScript: A Comparative Analysis for DevelopersPython vs. JavaScript: A Comparative Analysis for DevelopersMay 09, 2025 am 12:22 AM

The main difference between Python and JavaScript is the type system and application scenarios. 1. Python uses dynamic types, suitable for scientific computing and data analysis. 2. JavaScript adopts weak types and is widely used in front-end and full-stack development. The two have their own advantages in asynchronous programming and performance optimization, and should be decided according to project requirements when choosing.

Python vs. JavaScript: Choosing the Right Tool for the JobPython vs. JavaScript: Choosing the Right Tool for the JobMay 08, 2025 am 12:10 AM

Whether to choose Python or JavaScript depends on the project type: 1) Choose Python for data science and automation tasks; 2) Choose JavaScript for front-end and full-stack development. Python is favored for its powerful library in data processing and automation, while JavaScript is indispensable for its advantages in web interaction and full-stack development.

Python and JavaScript: Understanding the Strengths of EachPython and JavaScript: Understanding the Strengths of EachMay 06, 2025 am 12:15 AM

Python and JavaScript each have their own advantages, and the choice depends on project needs and personal preferences. 1. Python is easy to learn, with concise syntax, suitable for data science and back-end development, but has a slow execution speed. 2. JavaScript is everywhere in front-end development and has strong asynchronous programming capabilities. Node.js makes it suitable for full-stack development, but the syntax may be complex and error-prone.

JavaScript's Core: Is It Built on C or C  ?JavaScript's Core: Is It Built on C or C ?May 05, 2025 am 12:07 AM

JavaScriptisnotbuiltonCorC ;it'saninterpretedlanguagethatrunsonenginesoftenwritteninC .1)JavaScriptwasdesignedasalightweight,interpretedlanguageforwebbrowsers.2)EnginesevolvedfromsimpleinterpreterstoJITcompilers,typicallyinC ,improvingperformance.

JavaScript Applications: From Front-End to Back-EndJavaScript Applications: From Front-End to Back-EndMay 04, 2025 am 12:12 AM

JavaScript can be used for front-end and back-end development. The front-end enhances the user experience through DOM operations, and the back-end handles server tasks through Node.js. 1. Front-end example: Change the content of the web page text. 2. Backend example: Create a Node.js server.

Python vs. JavaScript: Which Language Should You Learn?Python vs. JavaScript: Which Language Should You Learn?May 03, 2025 am 12:10 AM

Choosing Python or JavaScript should be based on career development, learning curve and ecosystem: 1) Career development: Python is suitable for data science and back-end development, while JavaScript is suitable for front-end and full-stack development. 2) Learning curve: Python syntax is concise and suitable for beginners; JavaScript syntax is flexible. 3) Ecosystem: Python has rich scientific computing libraries, and JavaScript has a powerful front-end framework.

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

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Linux new version

SublimeText3 Linux new version

SublimeText3 Linux latest version

MantisBT

MantisBT

Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.