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!

Different 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.

JavaScript'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.

I 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

This article demonstrates frontend integration with a backend secured by Permit, building a functional EdTech SaaS application using Next.js. The frontend fetches user permissions to control UI visibility and ensures API requests adhere to role-base

JavaScript is the core language of modern web development and is widely used for its diversity and flexibility. 1) Front-end development: build dynamic web pages and single-page applications through DOM operations and modern frameworks (such as React, Vue.js, Angular). 2) Server-side development: Node.js uses a non-blocking I/O model to handle high concurrency and real-time applications. 3) Mobile and desktop application development: cross-platform development is realized through ReactNative and Electron to improve development efficiency.

The latest trends in JavaScript include the rise of TypeScript, the popularity of modern frameworks and libraries, and the application of WebAssembly. Future prospects cover more powerful type systems, the development of server-side JavaScript, the expansion of artificial intelligence and machine learning, and the potential of IoT and edge computing.

JavaScript is the cornerstone of modern web development, and its main functions include event-driven programming, dynamic content generation and asynchronous programming. 1) Event-driven programming allows web pages to change dynamically according to user operations. 2) Dynamic content generation allows page content to be adjusted according to conditions. 3) Asynchronous programming ensures that the user interface is not blocked. JavaScript is widely used in web interaction, single-page application and server-side development, greatly improving the flexibility of user experience and cross-platform development.

Python is more suitable for data science and machine learning, while JavaScript is more suitable for front-end and full-stack development. 1. Python is known for its concise syntax and rich library ecosystem, and is suitable for data analysis and web development. 2. JavaScript is the core of front-end development. Node.js supports server-side programming and is suitable for full-stack development.


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

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

VSCode Windows 64-bit Download
A free and powerful IDE editor launched by Microsoft

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.

ZendStudio 13.5.1 Mac
Powerful PHP integrated development environment

WebStorm Mac version
Useful JavaScript development tools