Home > Web Front-end > JS Tutorial > Let's talk about how to use node to write and read file content

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

青灯夜游
Release: 2022-12-22 20:58:10
forward
2605 people have browsed it

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);// 打印成功的结果
})
Copy after login

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);
})
Copy after login

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('文件写入成功!');
})
Copy after login

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('写入成功!');
    })
})
Copy after login

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);
})
Copy after login

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);
Copy after login
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);
})
Copy after login

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);
Copy after login

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
Copy after login

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!

Related labels:
source:csdn.net
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template