Manually Parsing HTML in Node.js

/*
    This code comes from Vincent Lab
    And it has a video version linked here: https://www.youtube.com/watch?v=PozG7Sva270
*/

// Import dependencies
const fs = require("fs");
const cheerio = require("cheerio");
const cheerioTableparser = require("cheerio-tableparser");

// Get all the filenames from the customers folder
const files = fs.readdirSync("customers");

// All of the parse customers
let customers = [];

// For each file in the customers folder
for (const file of files) {

    // The parse customer
    let customer = {};

    // Get the HTML out of the file
    const html = fs.readFileSync(`customers/${file}`).toString();

    // Convert the HTML to a cheerio dom element
    const $ = cheerio.load(html);

    // Run HTML through table parser
    cheerioTableparser($);

    // Parse the table and turn it into an array
    let table = $("table").parsetable();

    // Check if it's format one or format two
    if (table[1][2].match(/\d+-\d+-\d+/) !== null) {

        // Add the data from the table to the customer object
        customer = {
            name: table[1][0],
            telephone: [table[1][1], table[1][2]],
            birthday: table[1][3],
            emailAddress: table[1][4],
            employment: table[1][5],
            vehicle: table[1][6],
            bank: table[1][7],
        }

    } else {

        // Add the data from the table to the customer object
        customer = {
            name: table[1][0],
            telephone: table[1][1],
            birthday: table[1][2],
            emailAddress: table[1][3],
            employment: table[1][4],
            vehicle: table[1][5],
            bank: table[1][6],
        }

    }

    // Add the customer to the customers array
    customers.push(customer);
}

// Save the extracted information to a json file
fs.writeFileSync("customers.json", JSON.stringify(customers));

Are there any code examples left?
Made with love
This website uses cookies to make IQCode work for you. By using this site, you agree to our cookie policy

Welcome Back!

Sign up to unlock all of IQCode features:
  • Test your skills and track progress
  • Engage in comprehensive interactive courses
  • Commit to daily skill-enhancing challenges
  • Solve practical, real-world issues
  • Share your insights and learnings
Create an account
Sign in
Recover lost password
Or log in with

Create a Free Account

Sign up to unlock all of IQCode features:
  • Test your skills and track progress
  • Engage in comprehensive interactive courses
  • Commit to daily skill-enhancing challenges
  • Solve practical, real-world issues
  • Share your insights and learnings
Create an account
Sign up
Or sign up with
By signing up, you agree to the Terms and Conditions and Privacy Policy. You also agree to receive product-related marketing emails from IQCode, which you can unsubscribe from at any time.
Creating a new code example
Code snippet title
Source