concept Nightmare in category data

appears as: Nightmare
Data Wrangling with JavaScript

This is an excerpt from Manning's book Data Wrangling with JavaScript.

Nightmare is the headless browser we’ll use. It’s a Node.js library (installed using npm) that’s built on Electron. Electron is a web browser that’s normally used for building cross-platform desktop apps that are based on web technologies. We don’t need to directly interact with or understand how to use Electron; we’ll interact with it only through Nightmare, and we can think of Electron as if it were a standard web browser.

Now let’s replace the placeholder comment from listing 11.3b with code that captures a screenshot of our visualization. Listing 11.4 has new code that instances Nightmare, points it at our web server, and then takes a screenshot. You can run this code, and it will render the chart and produce the file nyc-temperatures.png to the output subdirectory under the listing-11.4 directory.

Listing 11.4 Capturing the chart to an image file using Nightmare (listing-11.4/index.js)
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 we started
#4   Waits until an svg element appears onscreen, indicating that the chart has loaded
#5   Captures a screenshot to an image file
#6   Ends the Nightmare session. Any queued operations are completed, and the headless browser is terminated.
#7   Stops the web server when we’re done