如何在节点js中多次覆盖并将数据附加到同一个文件

我有一个“clients.txt”文件,其中有一个电子邮件列表。我尝试运行一个发送电子邮件的程序,我从文件中选择了一些要使用的电子邮件,在这种情况下,数字是 2。在我使用这两封电子邮件后,我想在没有它们的情况下覆盖“clients.txt”。问题是当我尝试只运行一次代码时,一切正常!但是如果我做一个循环,就会出现问题。期待看到你们的任何帮助。谢谢!我在下面添加代码。PS:抱歉我的英语不好!


function readEmails(){

    const fs = require('fs');

    clients_list = fs.readFileSync('clients.txt', 'utf8').split('\n');

    let filtered = clients_list.filter(function (el) {

        return el != null && el != '';

    });

    return filtered

}

function dump_array(arr, file){

    let fs = require('fs');

    let file = fs.createWriteStream(file);

    file.on('error', function(err) { /* error handling */ });

    arr.forEach(function(v) { file.write(v + '\n'); });

    file.end();

}


while_var = 0;

while (while_var < 2){

    while_var ++;

    let all_clients = readEmails();

    let selected_clients = [];

    if (all_clients.length > 0){

        selected_clients = all_clients.splice(0,2);

        dump_array(all_clients, 'clients.txt');

        console.log(selected_clients);

    }else{

        console.log('No more clients')

    }

}


慕神8447489
浏览 85回答 1
1回答

慕婉清6462132

const fs = require('fs');function readEmails(){&nbsp; &nbsp; const clients_list = fs.readFileSync('clients.txt', 'utf8').split('\n');&nbsp; &nbsp; const filtered = clients_list&nbsp; &nbsp; &nbsp; &nbsp; // clear false, 0 and undefined too&nbsp; &nbsp; &nbsp; &nbsp; .filter(el => !!el)&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; // remove extra spaces and \r symbols&nbsp; &nbsp; &nbsp; &nbsp; .map(el => el.trim());&nbsp;&nbsp; &nbsp; return filtered;}function dump_array(arr, file){&nbsp; &nbsp; // Here you need sync method.&nbsp;&nbsp; &nbsp; fs.writeFileSync(file, arr.join('\n'));&nbsp;&nbsp; &nbsp; // And here was 'already declared' error in orginal code}let while_var = 0;while (while_var++ < 2){&nbsp; &nbsp; let all_clients = readEmails();&nbsp; &nbsp; let selected_clients = [];&nbsp; &nbsp; if (all_clients.length > 0){&nbsp; &nbsp; &nbsp; &nbsp; selected_clients = all_clients.splice(0,2);&nbsp; &nbsp; &nbsp; &nbsp; dump_array(all_clients, 'clients.txt');&nbsp; &nbsp; &nbsp; &nbsp; console.log(selected_clients);&nbsp; &nbsp; }else{&nbsp; &nbsp; &nbsp; &nbsp; console.log('No more clients')&nbsp; &nbsp; }}
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript