簡體   English   中英

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

[英]How can I overwrite and append data to the same file multiple times in node 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')
    }
}
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')
    }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM