Process in Data Wrangling with JavaScript

Overview of the Data-Wrangling Process

The data-wrangling process is a comprehensive approach that involves several key stages: acquiring, exploring, understanding, and visualizing data. The ultimate goal of this process is to prepare data for production use, whether it be for a web visualization or a detailed report. This process ensures that data is clean, structured, and ready for analysis or presentation.

Parallel Processing with Slave and Master Scripts

In the context of data wrangling, processing large datasets efficiently is crucial. This is where parallel processing comes into play, utilizing both slave and master scripts to handle data in chunks or windows.

[Slave Process (Listing 8.8)](https://livebook.manning.com/book/data-wrangling-with-javascript/chapter-1/79)

The slave process is responsible for handling a specific window of data. It operates by receiving parameters that define the position and size of the data window, using skip and limit command-line arguments. The script then processes this data window, allowing for custom data processing code to be inserted at a designated point.

Listing 8.8 The slave process that does the work in parallel (listing-8.8.js)

// ... openDatabase function is omitted ...

function processData (collection, skipAmount, limitAmount) {   
 return collection.find()   
 .skip(skipAmount)   
 .limit(limitAmount)   
        .toArray()
 .then(data => {   
            console.log(">> Your code to process " + data.length + " ➥ records here!");
 });   
};   

console.log("Processing records " + argv.skip + " to " + (argv.skip + ➥ argv.limit));

openDatabase()
    .then(db => {
 return processData(db.collection, argv.skip, argv.limit)   
            .then(() => db.close());
    })
    .then(() => {
        console.log(
            "Done processing records " + argv.skip +
            " to " + (argv.skip + argv.limit)
        );
    })
    .catch(err => {
        console.error(
            "An error occurred processing records " + argv.skip +
            " to " + (argv.skip + argv.limit)
        );
        console.error(err);
    });

[Master Process (Listing 8.9)](https://livebook.manning.com/book/data-wrangling-with-javascript/chapter-1/79)

The master process coordinates the execution of multiple slave processes. It manages the workload by firing off a set number of slave processes concurrently, waiting for them to complete, and then initiating the next set. This approach is scalable, allowing the number of concurrent processes to be adjusted based on available CPU resources.

Listing 8.9 The master process that coordinates the slave processes (listing-8.9.js)

const argv = require('yargs').argv;
const spawn = require('child_process').spawn;   
const parallel = require('async-await-parallel');

// ... openDatabase function is omitted ...

function runSlave (skip, limit, slaveIndex) {   
 return new Promise((resolve, reject) => {   
 const args = [   
 "listing-8.8.js",   
 "--skip",   
 skip,   
 "--limit",   
 limit   
 ];   

 const childProcess = spawn("node", args);   

    // … input redirection omitted …

 childProcess.on("close", code => {   
            if (code === 0) {
 resolve();   
            }
            else {
 reject(code);   
            }
 });   

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

function processBatch (batchIndex, batchSize) {   
 const startIndex = batchIndex * batchSize;   
 return () => {   
 return runSlave(startIndex, batchSize, batchIndex);   
 };   
};   

function processDatabase (numRecords) {   

 const batchSize = 100;   
 const maxProcesses = 2;   
 const numBatches = numRecords / batchSize;   
 const slaveProcesses = [];   
 for (let batchIndex = 0; batchIndex < numBatches; ++batchIndex) {   
 slaveProcesses.push(processBatch(batchIndex, batchSize));   
 }   

    return parallel(slaveProcesses, maxProcesses);
};   

openDatabase()
    .then(db => {
 return db.collection.find().count()   
 .then(numRecords => processDatabase (numRecords))   
            .then(() => db.close());
    })
    .then(() => {
        console.log("Done processing all records.");
    })
    .catch(err => {
        console.error("An error occurred reading the database.");
        console.error(err);
    });

In this setup, the master script first determines the total number of records in the database. It then divides the data into manageable windows and processes each window by invoking the slave script. The use of promises and asynchronous operations ensures that the system efficiently handles multiple processes without blocking the main execution thread. This method is particularly effective for large datasets, as it leverages parallel processing to reduce overall processing time.