Let'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!
Node.js is a JavaScript running environment based on the Chrome V8 engine. [Related tutorial recommendations: nodejs video tutorial, Programming teaching】
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);// 打印成功的结果 })
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
Failed
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('文件写入成功!'); })
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!

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

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics

How to delete node with nvm: 1. Download "nvm-setup.zip" and install it on the C drive; 2. Configure environment variables and check the version number through the "nvm -v" command; 3. Use the "nvm install" command Install node; 4. Delete the installed node through the "nvm uninstall" command.

How to handle file upload? The following article will introduce to you how to use express to handle file uploads in the node project. I hope it will be helpful to you!

This article will share with you Node's process management tool "pm2", and talk about why pm2 is needed, how to install and use pm2, I hope it will be helpful to everyone!

Detailed explanation and installation guide for PiNetwork nodes This article will introduce the PiNetwork ecosystem in detail - Pi nodes, a key role in the PiNetwork ecosystem, and provide complete steps for installation and configuration. After the launch of the PiNetwork blockchain test network, Pi nodes have become an important part of many pioneers actively participating in the testing, preparing for the upcoming main network release. If you don’t know PiNetwork yet, please refer to what is Picoin? What is the price for listing? Pi usage, mining and security analysis. What is PiNetwork? The PiNetwork project started in 2019 and owns its exclusive cryptocurrency Pi Coin. The project aims to create a one that everyone can participate

How to package nodejs executable file with pkg? The following article will introduce to you how to use pkg to package a Node project into an executable file. I hope it will be helpful to you!

Authentication is one of the most important parts of any web application. This tutorial discusses token-based authentication systems and how they differ from traditional login systems. By the end of this tutorial, you will see a fully working demo written in Angular and Node.js. Traditional Authentication Systems Before moving on to token-based authentication systems, let’s take a look at traditional authentication systems. The user provides their username and password in the login form and clicks Login. After making the request, authenticate the user on the backend by querying the database. If the request is valid, a session is created using the user information obtained from the database, and the session information is returned in the response header so that the session ID is stored in the browser. Provides access to applications subject to

How to run node in IDEA? The following article will introduce to you how to configure, install and run node.js in IDEA. I hope it will be helpful to you!

The node server.js error is because the path is incorrect. The solution is: 1. Enter the cmd window; 2. Switch to "server.js" under the project path; 3. Re-execute the "node server.js" command to solve the error problem. .
