Home > Web Front-end > Front-end Q&A > How to modify file content in nodejs

How to modify file content in nodejs

青灯夜游
Release: 2023-01-11 09:20:34
Original
8962 people have browsed it

Nodejs method to modify file content: 1. Use "fs.writeFile(path,data,callback:(err)=>void)" method; 2. Use "fs.open(path,(err) ,fd)=>{})" to open the file, and then write data through the file descriptor fd.

How to modify file content in nodejs

The operating environment of this tutorial: windows7 system, nodejs version 14.15.4, DELL G3 computer.

In nodejs, you can use the built-in method of the file system module (fs for short) to modify the file content.

Modify the file content

Write data to the file. The data can be a string or buffer: fs.writeFile(path,data,callback:(err )=>void)

fs.writeFile('message.txt', data, (err) => {
  if (err) throw err;
});
Copy after login

There is another way to write a file through the file descriptor fd:

fs.open(path,(err,fd)=>{
    //针对拿到的fd 进行操作:将buffer内容写如fd对应的文件里
    //position为文件的起点
    //length为待写的长度
    //offset为缓存区起写的位置
    fs.write(fd,buffer,offset,length,position,(err,bytesWrittenLen,buffer)=>{

    })
    //关闭文件
    fs.close(fd, (err) => {
        if (err) throw err;
    });
})
Copy after login

Example: read the file and modify the file Content

const fs = require('fs');
const path = require('path');
const newList = [];
fs.readFile(path.join(__dirname, './json/hp_mph.json'), 'utf8', function (err, data) {
    if (err) throw err;
    let list = JSON.parse(data);
    // list.forEach((item,index)=>{
    //     let value = item.properties;
    //     let result = {};  
    //     result.ID = index + 1;
    //     result.TYPE = value.FLAG_A;
    //     result.X = value.X;
    //     result.Y = value.Y;
    //     newList.push(result);
    // })
 
    for (let i = 0; i < list.length; i++) {
        let result = {};
        let value = list[i].properties;
        result.ID = i + 1;
        result.TYPE = value.FLAG_A;
        result.X = value.X;
        result.Y = value.Y;
        newList.push(result);
    }
 
    let newContent = JSON.stringify(newList, null, 4);
    fs.writeFile(&#39;result.json&#39;, newContent, &#39;utf8&#39;, (err) => {
        if (err) throw err;
        console.log(&#39;success done&#39;);
    });
});
Copy after login

[Recommended learning: "nodejs tutorial"]

The above is the detailed content of How to modify file content in nodejs. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
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