node.js - 关于查找字符串和删除行的问题 - Node.JS
问题描述
var fs = require('fs')
fs.readFile('shuffle.txt', {encoding: 'utf-8'}, function(err, data) {
if (err) throw error;
let dataArray = data.split('\n'); // convert file data in an array
const searchKeyword = 'user1'; // we are looking for a line, contains, key word 'user1' in the file
let lastIndex = -1; // let say, we have not found the keyword
for (let index=0; index<dataArray.length; index++) {
if (dataArray[index].includes(searchKeyword)) { // check if a line contains the 'user1' keyword
lastIndex = index; // found a line includes a 'user1' keyword
break;
}
}
dataArray.splice(lastIndex, 1); // remove the keyword 'user1' from the data Array
// UPDATE FILE WITH NEW DATA
// IN CASE YOU WANT TO UPDATE THE CONTENT IN YOUR FILE
// THIS WILL REMOVE THE LINE CONTAINS 'user1' IN YOUR shuffle.txt FILE
const updatedData = dataArray.join('\n');
fs.writeFile('shuffle.txt', updatedData, (err) => {
if (err) throw err;
console.log ('Successfully updated the file data');
});
});
此链接说明了如何查找字符串并删除行,但当时只删除一个 user1。我与 user1 有很多行,如何删除所有行:
john
doe
some keyword
user1
last word
user1
user1
也相反。如何删除所有行并仅保留 user1 行?
解决方案
我会使用Array.filter()函数。
基本上,您调用filter()
一个数组,并定义一个回调函数来检查该数组的每个项目。
如果检查函数返回true
特定项目,则保留该项目 - 将其放入新数组 如果检查函数返回false
,则不要将项目放入新数组
因此,在您的情况下,一旦您将所有行读入数组(代码中的第 6 行),请使用 filter 函数:
// Delete all instances of user1
let newDataArray = dataArray.filter(line => line !== "user1")
// Delete everything except user1
let newDataArray = dataArray.filter(line => line === "user1")
// Delete any lines that have the text 'user1' somewhere inside them
let newDataArray = dataArray.filter(line => !line.includes("user1"))
然后,就像您在代码中所做的那样,使用join()
函数newDataArray()
并写入文件。
要重写您的代码,
var fs = require('fs')
fs.readFile('shuffle.txt', {encoding: 'utf-8'}, function(err, data) {
if (err) throw error;
let dataArray = data.split('\n'); // convert file data in an array
const searchKeyword = 'user1'; // we are looking for a line, contains, key word 'user1' in the file
// Delete all instances of user1
let newDataArray = dataArray.filter(line => line !== searchKeyword)
// UPDATE FILE WITH NEW DATA
const updatedData = newDataArray.join('\n');
fs.writeFile('shuffle.txt', updatedData, (err) => {
if (err) throw err;
console.log ('Successfully updated the file data');
});
});
推荐阅读
- algorithm - 拼接并插入一个数组到另一个
- c# - 想要评估多项式方程
- asp.net-mvc - 我做了依赖注入,但值在 asp.net mvc 中返回 null
- ssl - 在 HTTPS 中解密数据时
- jquery - 在 ASP.NET MVC 中创建可从客户端(jquery)和服务器访问的全局变量的最佳方法
- google-cloud-firestore - 在 Firestore 安全规则中映射字段
- c++ - Unicode 和 SetWindowsHookEx
- javascript - 如何在上传 AWS Lambda 层时更改对它的引用?
- python - ValueError:拆分线时没有足够的值来解包(预期为 2,得到 1)
- html - HTML表格行内的Angular ng-container