Home > Article > Web Front-end > nodejs delete specified content of file
Node.js is currently the most popular server-side JavaScript running environment. It provides a series of powerful APIs and libraries that allow developers to easily handle files, networks, and other operations. In this article, we will learn how to delete specified content from a file using Node.js.
To delete specified content in a file, we need to follow these steps:
The code below demonstrates how to perform these steps:
const fs = require('fs'); function deleteContentFromFile(filePath, contentToDelete) { //打开文件并读取内容 const content = fs.readFileSync(filePath, { encoding: 'utf-8' }); //查找并删除指定内容 const modifiedContent = content.replace(contentToDelete, ''); //将修改后的内容写回文件中 fs.writeFileSync(filePath, modifiedContent); } //使用示例 deleteContentFromFile('test.txt', '要删除的内容');
In the above code, we used Node.js’ file system module (fs
) to read and write files. The fs.readFileSync()
method is used to read the contents of the file synchronously and decode it into a string using utf-8
encoding. Next, we use the replace()
method of the string to delete the specified content and save the modified content in the variable modifiedContent
. Finally, we use the fs.writeFileSync()
method to write the modified content back to the source file.
To delete specified content in a file using the code above, save it as a file called deleteContentFromFile.js
and pass the content to be deleted and the file path as parameters to deleteContentFromFile()
Function is enough.
Summary:
It is not difficult to delete the specified content in the file using Node.js, just follow the above steps. It should be noted that when writing the modified content back to the file, we use the synchronous fs.writeFileSync()
method, which means that the program will block until the file content is written. If you wish to write to a file without blocking the main thread, use the asynchronous fs.writeFile()
method.
The above is the detailed content of nodejs delete specified content of file. For more information, please follow other related articles on the PHP Chinese website!