Reading content from URL with Node.js

前端 未结 4 1171
情深已故
情深已故 2020-12-02 20:12

I\'m trying to read the content from a URL with Node.js but all I seem to get are a bunch of bytes. I\'m obviously doing something wrong but I\'m not sure what. This is the

4条回答
  •  一生所求
    2020-12-02 21:01

    HTTP and HTTPS:

    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 = '';
    
                // A chunk of data has been recieved.
                resp.on('data', (chunk) => {
                    data += chunk;
                });
    
                // The whole response has been received. Print out the result.
                resp.on('end', () => {
                    resolve(data);
                });
    
            }).on("error", (err) => {
                reject(err);
            });
        });
    };
    
    (async (url) => {
        console.log(await getScript(url));
    })('https://sidanmor.com/');
    

提交回复
热议问题