首页 > 解决方案 > 关于查找字符串和删除行的问题 - 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 行?

标签: node.jsreadlines

解决方案


我会使用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');
  });

});

推荐阅读