node express | display the output from express | save a list of image elements | Search

This code initializes an asynchronous operation that makes a request to a specified URL, processes the response to extract image sources, and updates an array with the sources. It also includes error handling to notify the operation in case of any errors that occur during the process.

Run example

npm run import -- "run a DOM query on a remote HTML page"

run a DOM query on a remote HTML page

$.async();
var images = [];
new Promise((resolve, reject) => {
    request('http://' + host + ':' + port, (err, res, body) => {
        if (err) {
            reject(err)
        }
        else {
            resolve(body)
        }
    });
}).then((body) => {
    var nodeList = (new JSDOM(body)).window.document.querySelectorAll(query);
    return Array.prototype.slice.call(nodeList, 0)
        .map(i => i.getAttribute('src'));
}).then(sources => {
    images = sources;
    $.done(sources);
}).catch(e => $.done(e));

What the code could have been:

// Import necessary libraries
import { JSDOM } from 'jsdom';
import axios from 'axios';

/**
 * Asynchronously fetches images from the webpage at the given host and port.
 * @param {string} host - The hostname of the webpage.
 * @param {number} port - The port number of the webpage.
 * @param {string} query - The CSS query to select image elements.
 * @param {function} callback - The callback function with the images and any error.
 */
async function fetchImages(host, port, query, callback) {
  try {
    // Fetch the webpage using axios
    const response = await axios.get(`http://${host}:${port}`);

    // Parse the HTML using JSDOM
    const dom = new JSDOM(response.data);
    const nodeList = dom.window.document.querySelectorAll(query);

    // Extract the image sources
    const sources = Array.prototype.slice.call(nodeList).map(i => i.getAttribute('src'));

    // Call the callback function with the images
    callback(null, sources);
  } catch (error) {
    // Call the callback function with the error
    callback(error);
  }
}

// Example usage
fetchImages('example.com', 80, 'img[src]', (error, images) => {
  if (error) {
    // Handle error
  } else {
    console.log(images);
  }
});

Code Breakdown

Initialization

Making a Request

Processing the Response

Updating the Images Array

Error Handling