亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

如何在節點js中多次覆蓋并將數據附加到同一個文件

如何在節點js中多次覆蓋并將數據附加到同一個文件

慕神8447489 2023-05-25 15:42:21
我有一個“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')    }}
查看完整描述

1 回答

?
慕婉清6462132

TA貢獻1804條經驗 獲得超2個贊

const fs = require('fs');


function readEmails(){

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

    const filtered = clients_list

        // clear false, 0 and undefined too

        .filter(el => !!el) 

        // remove extra spaces and \r symbols

        .map(el => el.trim()); 

    return filtered;

}

function dump_array(arr, file){

    // Here you need sync method. 

    fs.writeFileSync(file, arr.join('\n')); 

    // And here was 'already declared' error in orginal code

}


let while_var = 0;

while (while_var++ < 2){

    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')

    }

}


查看完整回答
反對 回復 2023-05-25
  • 1 回答
  • 0 關注
  • 148 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號