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.
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('result.json', newContent, 'utf8', (err) => { if (err) throw err; console.log('success done'); }); });
[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!