【问题标题】:JavaScript forEach: How can I count the number of lines written by the forEach function?JavaScript forEach:如何计算 forEach 函数写入的行数?
【发布时间】:2021-09-08 01:17:27
【问题描述】:

目前我的代码是:

var ProxyVerifier = require('proxy-verifier');
const fs = require('fs');
var request = require('request');
const { doesNotMatch } = require('assert');

let config = {
    file: 'socks4_proxies.txt',
    destFile: 'result.txt'
}

function countFileLines(filePath) {
    return new Promise((resolve, reject) => {
        let lineCount = 0;
        fs.createReadStream(filePath)
            .on("data", (buffer) => {
                let idx = -1;
                lineCount--; // Because the loop will run once for idx=-1
                do {
                    idx = buffer.indexOf(10, idx + 1);
                    lineCount++;
                } while (idx !== -1);
            }).on("end", () => {
                resolve(lineCount);
            }).on("error", reject);
    });
};

function getProxies() {
    return new Promise(function (resolve, reject) {
        request.get('https://api.proxyscrape.com/?request=displayproxies&proxytype=socks4&timeout=2500', function (error, response, body) {
            if (!error && response.statusCode == 200) {
                resolve(body);
                console.log('Proxies pulled!')
            } else {
                console.log(`Oops, ProxyScrape is down! Please try again later / contact me`)
            }
        });
    });
}

async function proxyTestLogic(proxy_list, index) {
    var countLines = await countFileLines('file.txt')
    console.log(index)
    if (index > 150) {
        console.log('Ok good done you can stop now')
        return 'stop';
    } else {
        var splitProxy = proxy_list.split(':');
        var ipPortArr = [splitProxy[0], Number(splitProxy[1])]
        var proxy = {
            ipAddress: ipPortArr[0],
            port: ipPortArr[1],
            protocol: 'socks4'
        };

        ProxyVerifier.testAll(proxy, function (error, result) {
            if (error) {
            } else {
                if (result["protocols"]["socks4"]["ok"] == true) {
                    fs.appendFile('file.txt', ipPortArr[0] + ':' + ipPortArr[1] + '\n', (err) => {
                    });
                } else {
                }
            }
        });
    }
}

function testProxies(proxies) {
    return new Promise(function (resolve, reject) {
        let newLined = proxies.replace(/\r|\"/gi, '').split("\n")
        newLined.forEach((item, index) => {
            proxyTestLogic(item, index)
        })
    })
}

async function main() {
    let proxies = await getProxies();
    testProxies(proxies)
}

main();

如您所见,它是一个代理验证器。它使用 forEach 函数计算数组中的每个代理。我试图让它停止在写入 socks4_proxies.txt 的 x 行数处,当我在其上启用 console.log 功能时,它只会输出同一行 1200 次(列表中的代理数量)。我该如何解决这个问题?

(我还应该提到我在 node.js 中编码)

谢谢, 吉布西尔

【问题讨论】:

    标签: javascript node.js arrays foreach proxies


    【解决方案1】:
    1. 不要在 .forEach 中执行异步代码,这永远不会像您期望的那样工作 - 使用常规 for 循环
    2. 使tetProxies异步
    3. 使用await proxytestLogic
    4. 摆脱 new Promise 反正你永远也解决不了

    所以 - 你最终得到:

    async function testProxies(proxies) {
        let newLined = proxies.replace(/\r|\"/gi, '').split("\n")
        for (let index=0; i < newLined.length; index++) {
                let result = await proxyTestLogic(newLined[index], index);
                if (result === 'stop')
                    break;
            })
        })
    }
    

    【讨论】:

    • 啊,我太慢了。确切的原因是您调用 forEach 处理程序的次数与代理数量一样多。
    • @AndreyPopov - 在开始下一个迭代之前,你永远不能“等待”每次迭代完成!
    • 我更进一步说,因为我们只是检查传递给indexproxyTestLogic,所以没有必要等待它或任何东西。它应该类似于for (let index = 0; index &lt; 150; index++)...就是这样:)
    • @AndreyPopov - 不太确定 - 在对 proxyTestLogic 的调用中计算了这些行 - 并且每个行可能不止一个......停止条件是该函数解析为 @ 987654331@ - 编辑:不,等等,是的......我现在明白了,我误解了该函数中的代码(说实话,看起来并不难,因为testProxies 显然是一团糟!!!跨度>
    • 有这条线if (index &gt; 150) {,所以它只是硬编码;)没有计算何时停止 - 它在 150。
    猜你喜欢
    • 2019-02-18
    • 1970-01-01
    • 2020-07-20
    • 2019-03-30
    • 1970-01-01
    • 2021-03-25
    • 2018-03-02
    • 2022-08-18
    • 2016-10-08
    相关资源
    最近更新 更多