【问题标题】:Find string and delete line - Node.JS查找字符串并删除行 - Node.JS
【发布时间】:2019-03-27 01:24:46
【问题描述】:

如何在 node.js 中读取文件、搜索字符串和删除行?我试过了

var fs = require('fs')
fs.readFile('shuffle.txt', function read(err, data) {
if (err) {
throw err;
}

lastIndex = function(){
for (var i = data_array.length - 1; i > -1; i--)
if (data_array[i].match('user1'))
return i;
}()

delete data_array[lastIndex];

});

【问题讨论】:

  • 一些问题。 'data_array' 在哪里被初始化?此外,您文件中的数据仅在回调函数中可用。 lastIndex 是一个函数,而不是一个值,因此 delete data_array[lastIndex] 可能不是您想要的。分解问题并一次测试。
  • 删除该行后,是否需要更新文件内容?
  • 是的,非常感谢您的回答。 javascript中是否也有任何解决方案?
  • 我用javascript写了答案。
  • 感谢您的帮助!如果它不是太多,你可以在这里帮助我:stackoverflow.com/questions/52935965/unirest-setting-proxy/…(顺便说一句,我只是指客户端 javascript,因为这是客户端 node.js?)

标签: node.js string file search fs


【解决方案1】:

假设我们有一个文本文件,shuffle.txt包含以下内容

john
doe
user1 
some keyword
last word

现在我们读取 shuffle.txt 文件,然后搜索“user1”关键字。如果任何一行包含“user1”,那么我们将删除该行。

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”关键字,我们将删除整行。新的 shuffle.txt 文件将不再包含带有 'user1' 关键字的行。更新后的 shuffle.txt 文件看起来像

john
doe
some keyword
last word

更多信息请查看doc

【讨论】:

    猜你喜欢
    • 2020-10-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-12-20
    相关资源
    最近更新 更多