void)" method; 2. Use "fs.open(path,(err,fd)=>{} )" opens the file and writes data through the file descriptor fd."/> void)" method; 2. Use "fs.open(path,(err,fd)=>{} )" opens the file and writes data through the file descriptor fd.">

Home  >  Article  >  Web Front-end  >  How to modify file content in nodejs

How to modify file content in nodejs

青灯夜游
青灯夜游Original
2021-09-16 13:00:588923browse

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;
});

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;
    });
})

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;);
    });
});

[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!

Statement:
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