JavaScript forEach:如何计算forEach函数写入的行数?
JavaScript forEach: How can I count the number of lines written by the forEach function?
目前我的代码是:
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 中编码)
谢谢,
吉宝
- 不要在
.forEach
中执行异步代码,它永远不会像您预期的那样工作 - 使用常规的 for 循环
- 使
tetProxies
异步
- 使用
await proxytestLogic
- 摆脱那个
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;
})
})
}
目前我的代码是:
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 中编码)
谢谢, 吉宝
- 不要在
.forEach
中执行异步代码,它永远不会像您预期的那样工作 - 使用常规的 for 循环 - 使
tetProxies
异步 - 使用
await proxytestLogic
- 摆脱那个
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;
})
})
}