Data Capture

Data capture is a critical process in data management, involving the immediate storage of incoming data into a database to ensure its safety and security. This step is essential to prevent data loss and is typically the first action taken after data is received from a sensor or data collection point. Capturing data before any processing minimizes risks and ensures that the raw data is preserved for future use.

Capturing Data with Nightmare

Nightmare is a high-level browser automation library that can be used to capture web pages and render them into image files or PDFs. This is particularly useful for visualizing data in charts or reports. Below are some examples of how Nightmare can be used for data capture.

Capturing a Chart to an Image File

The following code demonstrates how to capture a chart displayed on a web page and save it as an image file using Nightmare:

const webServer = require('./web-server.js');
const Nightmare = require('nightmare');

webServer.start()    #1  
    .then(server => {
        const outputImagePath = "./output/nyc-temperatures.png";

 const nightmare = new Nightmare();    #2  
 return nightmare.goto("http://localhost:3000")    #3  
 .wait("svg")    #4  
 .screenshot(outputImagePath)    #5  
 .end()    #6  
 .then(() => server.close());    #7  
    })
    .then(() => {
        console.log("All done :)");
    })
    .catch(err => {
        console.error("Something went wrong :(");
        console.error(err);
    })
  • #1: Starts the web server.
  • #2: Creates the Nightmare instance.
  • #3: Points the browser at the web server.
  • #4: Waits until an SVG element appears, indicating the chart has loaded.
  • #5: Captures a screenshot to an image file.
  • #6: Ends the Nightmare session.
  • #7: Stops the web server when done.

Capturing Specific Elements

To capture only specific parts of a web page, such as a chart, you can define a rectangle that limits the screenshot area:

function captureWebPage (urlToCapture, captureElementSelector, outputImagePath) {

    const nightmare = new Nightmare();
    return nightmare.goto(urlToCapture)
        .wait(captureElementSelector)
 .evaluate(captureElementSelector => {    #1  
 const body = document.querySelector("body");    #2  
 const captureElement =    #3  
 document.querySelector(captureElementSelector);    #3  
 const captureRect =    #4  
 captureElement.getBoundingClientRect();    #4  
 return {    #5  
 documentArea: {    #6  
                    width: body.scrollWidth,
                    height: body.scrollHeight
                },
 captureArea: {    #7  
                    x: captureRect.left,
                    y: captureRect.top,
                    width: captureRect.right - captureRect.left,
                    height: captureRect.bottom - captureRect.top
                }
            };
        }, captureElementSelector)
 .then(pageDetails => {    #8  
 return nightmare.viewport(    #9  
 pageDetails.documentArea.width,    #9  
 pageDetails.documentArea.height    #9  
 )    #9  
 .screenshot(outputImagePath, pageDetails.captureArea)    #10  
                .end();
        });
};
  • #1: Evaluates JavaScript code within the headless browser.
  • #2: Finds the body element of the web page.
  • #3: Finds the HTML element to be captured.
  • #4: Gets the area to capture.
  • #5: Returns details computed in the headless browser to Node.js.
  • #6: Returns the scrollable area of the page.
  • #7: Returns the rect of the area to capture.
  • #8: Retrieves details computed in the headless browser.
  • #9: Sets the viewport to cover the area of the chart.
  • #10: Captures a screenshot to an image file.

Rendering a Report to a PDF

Nightmare can also be used to render a web page to a PDF file, capturing the entire page:

function captureReport (urlToCapture,
 captureElementSelector, outputPdfFilePath) {    #1  

    const nightmare = new Nightmare();
    return nightmare.goto(urlToCapture)
        .wait(captureElementSelector)
        .evaluate(() => {
 const body = document.querySelector("body");    #2  
 return {    #3  
 documentArea: {    #4  
                    width: body.scrollWidth,
                    height: body.scrollHeight
                },
            };
        })
 .then(pageDetails => {    #5  
            const printOptions = {
 marginsType: 0,    #6  
 pageSize: {    #7  
 width: 297000,    #8  
 height: 210000,    #9  
                },
                landscape: true,
            };
 return nightmare.viewport(    #10  
 pageDetails.documentArea.width,    #10  
 pageDetails.documentArea.height    #10  
 )    #10  
 .pdf(outputPdfFilePath, printOptions)    #11  
                .end();
        });
};
  • #1: Captures a multipage report to a PDF file.
  • #2: Finds the body element of the web page.
  • #3: Returns details computed in the headless browser to Node.js.
  • #4: Returns the scrollable area of the page.
  • #5: Retrieves details computed in the headless browser.
  • #6: Specifies no margins.
  • #7: Lists the size of each page.
  • #8: Sets the width of the page.
  • #9: Sets the height of the page.
  • #10: Sets the viewport to cover the area of the chart.
  • #11: Captures the entire web page to a PDF report.

Error Handling

To handle errors during the capture process, you can attach an error handler to the Nightmare instance:

nightmare.on("console", function (type, message) {

 if (type === "log") {    #1  
 console.log("LOG: " + message);    #1  
 return;    #1  
    }

 if (type === "warn") {    #2  
 console.warn("LOG: " + message);    #2  
 return;    #2  
    }

 if (type === "error") {    #3  
 throw new Error("Browser JavaScript error: " + message);    #3  
 }    #3  
});
  • #1: Prints browser log messages to the Node.js console.
  • #2: Prints warning messages.
  • #3: JavaScript error messages throw an exception to abort the capture process.

Immediate Data Storage

To ensure data integrity, it is crucial to store received data into a database immediately before taking any further action. This approach is illustrated in the following figures:

Figure 12.11 Immediately store received data into our database before taking any further action. Figure 12.11 Immediately store received data into our database before taking any further action.

Figure 12.12 Using Robomongo to check that our incoming data has been captured to the database Figure 12.12 Using Robomongo to check that our incoming data has been captured to the database

By using tools like Robomongo, you can verify that the data has been successfully captured in the database, ensuring that no data is lost during the capture process.