You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Node.js中从指定URL生成字符串数组httpProxies

将远程TXT内容转换为每行元素的数组解决方案

需求说明

获取指定URL返回的TXT内容,创建名为httpProxies的数组,其中每一行内容作为数组的一个元素,预期输出示例:

console.log(httpProxies); // 返回 [ '78.110.195.242:7080', '144.86.187.56:8888', '64.225.4.85:9999', ...]

已实现内容获取的代码,但需要将获取到的文本转换为目标数组。

解决方案

只需在获取到文本内容后,通过字符串分割+空元素过滤即可实现需求,修改后的完整代码如下:

const getScript = (url) => {
  return new Promise((resolve, reject) => {
    const http = require('http'),
          https = require('https');

    let client = http;
    if (url.toString().indexOf("https") === 0) {
        client = https;
    }

    client.get(url, (resp) => {
        let data = '';

        resp.on('data', (chunk) => {
            data += chunk;
        });

        resp.on('end', () => {
            resolve(data);
        });

    }).on("error", (err) => {
        reject(err);
    });
  });
};

(async (url) => {
    // 获取远程TXT文本内容
    const textContent = await getScript(url);
    // 按换行分割为数组,并过滤无效空元素
    const httpProxies = textContent.split('\n').filter(item => item.trim() !== '');
    // 输出目标数组
    console.log(httpProxies);
})('https://raw.githubusercontent.com/monosans/proxy-list/main/proxies/http.txt');

关键步骤说明

  • 分割字符串:使用split('\n')将整个文本按换行符分割,把每行内容转为数组元素。
  • 过滤空元素:通过filter(item => item.trim() !== '')去除数组中的空字符串(比如文本末尾的空行、分割产生的无效元素),保证数组只包含有效的代理地址。

内容的提问来源于stack exchange,提问作者3jay1

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.16 05:12:39