How to import products from WooCommerce to Node.js

How to import products from WooCommerce to Node.js

WooCommerce provides us with an XML file for exporting its products. We can use this export file to import products into a Node.js e-commerce site.

WooCommerce provides us with an XML file for exporting its products. We can use this export file to import products into a Node.js e-commerce site.

First we need to install cheerio in order to parse the XML file:


npm install cheerio --save

cheerio features the same syntax of jQuery. The only thing to keep in mind is that namespace selectors must be escaped:


'use strict';

const cheerio = require('cheerio');
const fs = require('fs');


const importProducts = () => {
    const xml = fs.readFileSync(__dirname + '/dummy-data.xml' ).toString();
    const $ = cheerio.load(xml, {
        normalizeWhitespace: true,
        xmlMode: true
    });
    let data = [];
    $( 'item' ).each( (i, item) => {
        let product = $( item );
        let prod = {};
        let type = product.find('wp\\:post_type').text();

        if(type === 'product') {

            prod.title = product.find('title').text();
            prod.link =  product.find('link').text();
            prod.id = parseInt(product.find('wp\\:post_id').text(), 10);
            prod.date = product.find('wp\\:post_date').text();
            prod.content = product.find('content\\:encoded').text();
            prod.excerpt = product.find('excerpt\\:encoded').text();

            data.push(prod);
        }    
    });
    return data;
};

The WooCommerce export file also contains taxonomies and attachments so we need to make sure that the item we're selecting is a product. Here we are using cheerio in XML mode. Note that all namespace selectors are escaped. The export file used above can be seen in action on the official WooCommerce demo site.