Get the App
SLTechnology News&Howtos  ›  Development  › 

How nodejs modifies the contents of a file

Shulou Source: shulou.com Published: 2022-06-03 13:09:43 10月17日 Update

This article will explain in detail how nodejs modifies the contents of the file. The editor thinks it is very practical, so I share it for you as a reference. I hope you can get something after reading this article.

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

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

In nodejs, you can use the built-in methods of the File system Module (fs) to modify the contents of the file.

Modify the contents of the file

Writes data to a file, which 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) = > {/ / operate on the obtained fd: write the buffer content in the file corresponding to fd / / position as the starting point of the file / / length as the length to be written / / offset as the location to be written in the cache fs.write (fd,buffer,offset,length,position, (err,bytesWrittenLen,buffer) = > {}) / / close the file fs.close (fd (err) = > {if (err) throw err );})

Example: read a file and modify its contents

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');});}); this is the end of the article on "how to modify the contents of nodejs files". I hope the above content can be of some help to you, so that you can learn more knowledge. if you think the article is good, please share it for more people to see.

Tags: Files content data methods articles more systems good practical location characters strings tutorials articles methods modules environment computers knowledge examples Apple Docker Huawei Linux macOS MariaDB Microsoft MySQL NVidia OPPO Reno Linux Shulou Tech Info Shulou Information Shulou Technology MySQL