Home > OS >  How would I go about only selecting a certain number of lines with this code?
How would I go about only selecting a certain number of lines with this code?

Time:10-05

How would I go about only selecting a certain number of lines with this code? I have a rough understanding of using line but from that point I don't have a clue on how to ensure it only gets say for example 5 lines of accounts from the txt file or 10 accounts etc....

The code below is from a previous question I put on here: How to get more than 1 set of User:Pass from Accounts.txt

const readline = require("readline");
const fs = require("fs");

const rl = readline.createInterface({
    input: fs.createReadStream(__dirname   "/accounts.txt"),
});

rl.on("line", (line) => {
    const [username, password] = line.split(':');
    console.log(`${username}${password}`)
});

I've found a "Possible" solution but it doesn't stop counting when the number required is reached.

const line_counter = ((i = 0) => () =>   i)();

rl.on("line", (line, num = line_counter()) => {
    console.log(num)
    if (num === 10) {
        const [username, password] = line.split(':');
        console.log(`${username}${password}`);
        console.log("10")
    }
    //extra code
})

Little Explanation: I have a config system where it goes like so:

config = {
        "yourroleid": 1500,
        "yourroleid": 75,
        "yourroleid": 50,
        "yourroleid": 20,
        "yourroleid": 10,
        "yourroleid": 5
    } 

with this in mind, the person with said role(roleid) would only be able to get say for example 5 accounts or 10 accounts from the list. and it would ONLY do that many instead of a continuous "spam" of accounts.

CodePudding user response:

To accomplish the goal of exiting the readline early you are going to want to use the for await (const line of target) { syntax instead of the .on("line", method.

let limit = 0;
for await (const line of rl) {
    limit  ;
    const [user, pass] = line.split(":");
    //do stuff
    if (limit === 10) break;
}

Edited based on clarifying comments / conversation of goals

  • Related