<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Mackinley Levine on Medium]]></title>
        <description><![CDATA[Stories by Mackinley Levine on Medium]]></description>
        <link>https://medium.com/@mackplevine?source=rss-cefb8c104c20------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*EUpdpoiRrxgEVSv_XVipwQ.jpeg</url>
            <title>Stories by Mackinley Levine on Medium</title>
            <link>https://medium.com/@mackplevine?source=rss-cefb8c104c20------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Wed, 18 Nov 2026 10:21:47 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@mackplevine/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Mocking REST API Endpoints with Nock]]></title>
            <link>https://medium.com/@mackplevine/mocking-rest-api-endpoints-with-nock-20cce3d6f8d2?source=rss-cefb8c104c20------2</link>
            <guid isPermaLink="false">https://medium.com/p/20cce3d6f8d2</guid>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[nodejs]]></category>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[rest-api]]></category>
            <dc:creator><![CDATA[Mackinley Levine]]></dc:creator>
            <pubDate>Fri, 09 Dec 2016 06:49:15 GMT</pubDate>
            <atom:updated>2016-12-09T06:49:15.797Z</atom:updated>
            <content:encoded><![CDATA[<p>You may have been in a situation where a portion of the backend of your architecture was being replaced with a new database or technology (e.g. Salesforce) and you need to mock a REST API so the folks working on the client-facing portion of your app have something to interact with as they develop the front end.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*RbSgDoR19E6cBuZSpAL4ew.png" /></figure><p>You can do this with <a href="https://github.com/node-nock/nock">nock</a>, as long as you’re mocking server-to-server communication. Suppose a small part of the API for “Pizza Service” looked something like this:</p><pre>GET all chef names<br>chefs/</pre><pre>GET details for a specific chef<br>chefs/:chefId</pre><pre>GET all pizzas made by a given chef<br>chefs/:chefId/pizzas</pre><pre>GET pizza recipe details<br>chefs/:chefId/pizzas/:pizzaId</pre><p>You can mock responses for whatever existing HTTP requests Main Service makes with a handy library called nock.</p><p>My favorite way to do this is to create a mock object that has a property called ‘nock,’ the value of which is simply the mock for whatever base URI you’re using for your API. Here’s an ES6 class that instantiates objects with a ‘mock’ property (the fully implemented example class with tests can be found <a href="https://github.com/macklevine/pizzamock">here</a>):</p><pre>import nock from &#39;nock&#39;;<br>class PizzaMock {<br>  constructor() {<br>    this.mock = null;<br>  }<br>}</pre><p>Write some JSON files that will serve as the mock data nock will return in the response body for each endpoint. Here’s one for /chefs/:</p><pre>//chefs<br>[<br>  {<br>    &quot;name&quot; : &quot;Antonio Banderas&quot;,<br>    &quot;id&quot; : &quot;68c9db13-ea6b-4bbc-9b27-3f56a2d5c286&quot;<br>  },<br>  {<br>    &quot;name&quot; : &quot;Slavoj Zizek&quot;,<br>    &quot;id&quot; : &quot;cc866238-b579-4550-9d46-f06a5844dec5&quot;<br>  },<br>  {<br>    &quot;name&quot; : &quot;Carlos Santana&quot;,<br>    &quot;id&quot; : &quot;29e77cfe-db8c-4d66-a19a-4f63f752973b&quot;<br>  },<br>  {<br>    &quot;name&quot; : &quot;Gennady Golovkin&quot;,<br>    &quot;id&quot; : &quot;a8ea68cc-e227-4cb2-b2cc-d4c8d5fcada6&quot;<br>  }<br>]</pre><p>And here’s one for pizzas:</p><pre>//pizzas<br>[<br>  {<br>    &quot;name&quot; : &quot;Meatlovers&quot;,<br>    &quot;toppings&quot; : [&quot;Prosciutoo&quot;, &quot;Italian Sausage&quot;, &quot;Pepperoni&quot;, &quot;Salami&quot;]<br>  },<br>  {<br>    &quot;name&quot; : &quot;Del Mar&quot;,<br>    &quot;toppings&quot; : [&quot;Calamari&quot;, &quot;Shrimp&quot;, &quot;Garlic Sauce&quot;]<br>  },<br>  {<br>    &quot;name&quot; : &quot;The Shit-Show&quot;,<br>    &quot;toppings&quot; : [&quot;Jagermeister&quot;, &quot;Regret&quot;, &quot;Black Olives&quot;]<br>  }<br>]</pre><p>Now let’s expand our PizzaMock class to actually implement the mocks that will return this data. First, add a couple more import statements to pull in your mock data and declare whatever the base URL will be for the pizza service (of course, this can be configured with an environmental variable):</p><pre>import nock from &#39;nock&#39;;<br>import mockChefData from &#39;./mockdata/mockchefdata&#39;;<br>import mockPizzaData from &#39;./mockdata/mockpizzadata&#39;;</pre><pre>const baseUrl = &#39;<a href="http://www.mypizzaserver.com&/#39;">http://www.mypizzaserver.com&#39;</a>;</pre><pre>class PizzaMock {<br>  constructor() {<br>    this.mock = null;<br>  }<br>}</pre><p>Next, add an initMock() method and export the class:</p><pre>import nock from &#39;nock&#39;;<br>import mockChefData from &#39;./mockdata/mockchefdata&#39;;<br>import mockPizzaData from &#39;./mockdata/mockpizzadata&#39;;</pre><pre>const baseUrl = &#39;<a href="http://www.mypizzaserver.com&/#39;">http://www.mypizzaserver.com&#39;</a>;</pre><pre>class PizzaMock {<br>  constructor() {<br>    this.mock = null;<br>  }</pre><pre>initMock() {<br>    this.mock = nock(baseUrl);<br>    this.mock.persist()<br>      .filteringPath(path =&gt; {<br>        path = path.replace(/\/chefs\/[a-zA-Z0-9\-]{36}/g, &#39;/chefs/xxx&#39;);<br>        path = path.replace(/\/pizzas\/[a-zA-Z0-9\-]{36}/g, &#39;/pizzas/xxx&#39;);<br>        return path;<br>      });<br>    this.mock.persist()<br>      .get(&#39;/chefs&#39;)<br>      .query({count : &#39;1&#39;})<br>      .reply(200, {<br>        chefs : [mockChefData[0]]<br>      });<br>    this.mock.persist()<br>      .get(&#39;/chefs&#39;)<br>      .reply(200, {<br>        chefs: mockChefData<br>      });<br>    this.mock.persist()<br>      .get(&#39;/chefs/xxx&#39;)<br>      .reply(200, {<br>        chef: mockChefData[3]<br>      });<br>    this.mock.persist()<br>      .get(&#39;/chefs/xxx/pizzas&#39;)<br>      .reply(200, {<br>        pizzas: mockPizzaData<br>      });<br>    this.mock.persist()<br>      .get(&#39;./chefs/xxx/pizzas/xxx&#39;)<br>      .reply(200, {<br>        pizza: mockPizzaData[0]<br>      });<br>  }<br>}</pre><pre>export default PizzaMock;</pre><p>Let’s have a look at everything going on in this initMock() method.</p><p>The first thing we do is create a mock using our base URL:</p><pre>this.mock = nock(baseUrl);</pre><p>Next, we homogenize all of the calls to the API by replacing any unique identifiers/params in the URI with ‘xxx.’ The purpose of this is to enable our mock to send the same mock response for <em>any</em> request to a given endpoint, regardless of what the unique identifier is (e.g. a call to /chefs/3179b6c3–4e2a-40b5–9e67–25aa4a16f29d will return the same result as a call to /chefs/b4f631b9–77b4–4e15–904f-440b31f388f7).</p><pre>this.mock.persist()<br>      .filteringPath(path =&gt; {<br>        path = path.replace(/\/chefs\/[a-zA-Z0-9\-]{36}/g, &#39;/chefs/xxx&#39;);<br>        path = path.replace(/\/pizzas\/[a-zA-Z0-9\-]{36}/g, &#39;/pizzas/xxx&#39;);<br>        return path;<br>      });</pre><p>A couple of things worth noting about this implementation:</p><ul><li>Our specific mock assumes that the API always uses 36-character unique identifiers for each resource type, and the regex we use in each path.replace expression reflects this.</li><li>At the end of the callback function you provide filteringPath(), <strong>make sure you return the manipulated path!</strong></li></ul><p>Now that we’ve homogenized our paths, we can add mocks for each endpoint.</p><pre>    this.mock.persist()<br>      .get(&#39;/chefs&#39;)<br>      .query({count : &#39;1&#39;})<br>      .reply(200, {<br>        chefs : [mockChefData[0]]<br>      });<br>    this.mock.persist()<br>      .get(&#39;/chefs&#39;)<br>      .reply(200, {<br>        chefs: mockChefData<br>      });<br>    this.mock.persist()<br>      .get(&#39;/chefs/xxx&#39;)<br>      .reply(200, {<br>        chef: mockChefData[3]<br>      });<br>    this.mock.persist()<br>      .get(&#39;/chefs/xxx/pizzas&#39;)<br>      .reply(200, {<br>        pizzas: mockPizzaData<br>      });<br>    this.mock.persist()<br>      .get(&#39;./chefs/xxx/pizzas/xxx&#39;)<br>      .reply(200, {<br>        pizza: mockPizzaData[0]<br>      });</pre><p>Have a look at how I’ve mocked the /chefs endpoint. Among other handy utility options, one nice thing nock allows you to do is can customize responses based on the presence or absence of query parameters.</p><pre>this.mock.persist()<br>      .get(&#39;/chefs&#39;)<br>      .query({count : &#39;1&#39;})<br>      .reply(200, {<br>        chefs : [mockChefData[0]]<br>      });<br>    this.mock.persist()<br>      .get(&#39;/chefs&#39;)<br>      .reply(200, {<br>        chefs: mockChefData<br>      });</pre><p>Read the nock <a href="https://github.com/node-nock/nock">docs</a> to learn more.</p><p>Have fun!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=20cce3d6f8d2" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Using OAuth2 to Authenticate Node.js Web App Access to YouTube’s Data API]]></title>
            <link>https://medium.com/@mackplevine/using-oauth-to-authenticate-node-js-web-app-access-to-youtubes-data-api-46b4d430c6c5?source=rss-cefb8c104c20------2</link>
            <guid isPermaLink="false">https://medium.com/p/46b4d430c6c5</guid>
            <category><![CDATA[api]]></category>
            <category><![CDATA[youtube]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[nodejs]]></category>
            <category><![CDATA[oauth2]]></category>
            <dc:creator><![CDATA[Mackinley Levine]]></dc:creator>
            <pubDate>Fri, 09 Sep 2016 19:05:39 GMT</pubDate>
            <atom:updated>2016-09-09T20:48:25.758Z</atom:updated>
            <content:encoded><![CDATA[<p>Certain operations using YouTube’s data API require more than an API key — in some cases, you’ll need to use OAuth2. In this example (you can grab the complete code from my GitHub <a href="https://github.com/macklevine/youtube-oauth">here</a>), we’ll have a look at how to use OAuth to set up a web app to read the contents of a private playlist using Google’s Data API.</p><p>We’ll write a node module called YouTubeAuthService which has a handful of dependencies we’ll want to load at the top of the file:</p><pre>&#39;use strict&#39;;</pre><pre>var Promise = require(&#39;bluebird&#39;);<br>var google = require(&#39;googleapis&#39;);<br>var OAuth2 = google.auth.OAuth2;</pre><p>We’ll also want to set a handful of variables that should remain secret (make them configurable variables and don’t hard-code them into your project):</p><pre>var CLIENT_ID = process.env.CLIENT_ID;<br>var CLIENT_SECRET = process.env.CLIENT_SECRET;<br>var REDIRECT_URL = process.env.REDIRECT_URL;</pre><pre>var refresh_token = process.env.refresh_token;</pre><p>In order to get values for CLIENT_ID and CLIENT_SECRET, you’ll need to sign into the Google account associated with your YouTube channel and visit the <a href="https://console.developers.google.com/">Google Developer’s console</a>. (We’ll get the refresh_token value later after we visit the consent screen.)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*WE49QW8l2fw-PDZCBsxiVQ.png" /></figure><p>Click on ‘Create a project’ to register your web app:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/938/1*EJSd_2av1GpogTjA5pqIRA.png" /></figure><p>Agree to the terms and hit ‘create.’</p><p>You’ll get this dialog next:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*UbOM37nPQtAkso-mPKz5BA.png" /></figure><p>You’ll want to select ‘OAuth client ID.’ Configure a consent screen with a product name and be sure to select ‘Web application’ in the radio list for application type. Enter a name for your web app and hit Create.</p><p>You’ll want to copy your client ID and client secret in the modal that pops up and save them, because later, we’ll use them as values for the CLIENT_ID and CLIENT_SECRET environmental variables when you run the module we’re writing. (You’ll also want to enter a valid URL under <strong>Authorized redirect URIs</strong> — for our purposes, this can be any valid URL you’d like; I’ll explain why later.)</p><p>Next, you’ll want to choose what API you want your credentials to be able to access.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/672/1*aHatFuyQRN3lT1mf_ylQ5A.png" /></figure><p>Let’s enable YouTube’s Data API:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*I9CZmhtoZZQCri9U_z_5uw.png" /></figure><p>Next, we need to add at least one authorized redirect URL that we can be redirected to after we visit the consent screen. Make sure the URL is something valid (and don’t forget to hit save after you’ve added it).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*QcMJxc-QAgJ7io54E3z0EA.png" /></figure><p>Now that we have enabled the API we want to use, added one or more valid URLs for redirection, and obtained values for our client ID and client secret, we’re going to want to use these values to fetch a <strong>refresh token</strong>. This token does not expire and allows us to retrieve access tokens to make YouTube API requests on your behalf. Fetching this token is where the<strong> consent screen</strong> comes in.</p><p>To generate a consent screen, let’s first start implementing a YouTube API service in Node.js:</p><pre>var YouTubeAPIService = function YouTubeAPIService(){<br>  this.OAuth2Client = null;<br>  this.youtube = null;<br>};</pre><pre>YouTubeAPIService.prototype.initialize = function initialize(what){<br>  var self = this;<br>  if(what===&#39;Client&#39;){<br>    self.OAuth2Client = new OAuth2(CLIENT_ID, CLIENT_SECRET, REDIRECT_URL);<br>  }else if(what===&#39;Tokens&#39;){<br>    self.OAuth2Client.setCredentials({<br>      refresh_token: refresh_token<br>    });<br>    return new Promise(function(resolve, reject){<br>      self.refreshAccessToken()<br>        .then(function(response){<br>          console.log(self.OAuth2Client);<br>          self.youtube = google.youtube({<br>            version: &#39;v3&#39;,<br>            auth: self.OAuth2Client<br>          });<br>          resolve(&#39;YouTube oAuth client authenticated.&#39;);<br>        })<br>        .catch(function(err){<br>          console.log(err);<br>          reject(err);<br>        });<br>    });<br>  }<br>};</pre><pre>YouTubeAPIService.prototype.refreshAccessToken = function refreshAccessToken(){<br>  var self = this;<br>  return new Promise(function(resolve, reject){<br>    self.OAuth2Client.refreshAccessToken(function(err, tokens){<br>      if(err){<br>        //do something with the error<br>        console.log(err);<br>        return reject(&#39;error in authenticating YouTube oAuth client.&#39;);<br>      }<br>      resolve(tokens);<br>    });<br>  });<br>};</pre><p>The <strong>initialize </strong>method we’ve written will do one of two things depending on what argument we pass it:</p><ul><li>Create an OAuth2Client object as a property on an instance of the youTubeAPISservice class, which we will instantiate using the client ID and client secret values we retrieved from the Google Developer console earlier in addition to a redirect url.</li><li>Create a youtube client object on an instance of this class. We need to do this <em>after </em>we run initialize with the ‘Client’ argument, since the instantiation of the youtube object requires the service’s OAuth2Client property.</li></ul><p>For bullet 1, the redirect url value can actually be anything you want, since upon redirection you’ll find a string appended to the URL as a query parameter and this string is what we really care about when it comes to obtaining a refresh token.</p><p>Also note the second method above: <strong>refreshAccessToken. </strong>When passed a ‘Tokens’ argument, the initialize method of our class makes use of this method in order to use the refresh token to obtain an access token and set it as a credential on the OAuth2Client property of the class. (Note that after getting the tokens in the callback of self.OAuth2Client.refreshAccessToken, we don’t need to invoke OAuth2Client.setCredentials a second time with the newly fetched access token — the refreshAccessToken method takes care of this for us).</p><p>Finally, add a third method to your YouTubeAPIService class called generateAuthURL and export the contents of the module as an object constructor:</p><pre>YouTubeAPIService.prototype.generateAuthURL = function generateAuthURL(){<br>  var self = this;<br>  var url = self.OAuth2Client.generateAuthURL({<br>    access_type: &#39;offline&#39;,<br>    scope: &#39;<a href="https://gdata.youtube.com&/#39;">https://gdata.youtube.com&#39;</a><br>  });<br>  return url;<br>};</pre><pre>module.exports = YouTubeAPIService;</pre><p>This is what we’ll use to create our Authorization screen.</p><p>Now, require the YouTube API Service you’ve written in another module to use it and construct an instance of the service:</p><pre>&#39;use strict&#39;;</pre><pre>var YouTubeAPIService = require(&#39;./youtubeapiservice&#39;);<br>var youTubeAPIService = new YouTubeAPIService();</pre><pre>youTubeAPIService.initialize(&#39;Client&#39;);<br>console.log(youTubeAPIService.generateAuthURL());</pre><p>Initialize the service with the ‘Client’ argument, and then invoke the generateAuthURL method. When you run it, make sure to pass all of the necessary environment variables. Here’s an example of what this might look like:</p><pre>CLIENT_ID=20816xxx9000-01915787998v7kasqh2g8nmxxxbe20ni.apps.googleusercontent.com CLIENT_SECRET=HXeD1isebxxxxxg7I405y2L REDIRECT_URL=<a href="http://www.google.com/">http://www.google.com</a> node sampleusage.js</pre><p>You should get a URL for the consent screen logged to the console. Let’s visit this URL.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1020/1*0OxFoKvpYriBoUsL6laLfw.png" /></figure><p>Click ‘Allow’ and you’ll be redirected to the URL you passed in as the REDIRECT_URL environment variable, with a query parameter called ‘code’ appended to the URL string. Copy this value and save it.</p><p>Now let’s modify our YouTubeAPIService class and a fourth method called <strong>getToken</strong> to our prototype:</p><pre>YouTubeAPIService.prototype.getToken = function getToken(code){<br>  var self = this;<br>  self.OAuth2Client.getToken(code, function(err, tokens){<br>    console.log(tokens);<br>  });<br>};</pre><pre>module.exports = YouTubeAPIService;</pre><p>You’ll also want to modify your second module to invoke the getToken method after requiring and initializing an instance of youTubeAPIService:</p><pre>&#39;use strict&#39;;</pre><pre>var YouTubeAPIService = require(&#39;./youtubeapiservice&#39;);<br>var youTubeAPIService = new YouTubeAPIService();</pre><pre>youTubeAPIService.initialize(&#39;Client&#39;);<br>youTubeAPIService.getToken();</pre><p>When you run this second module again with the same values for CLIENT_ID, CLIENT_SECRET and REDIRECT_URL, it will log an object to the console that should contain a property called <strong>refresh_token</strong>. Save this value.</p><p>Now, let’s rewrite our second module to run the .initialize() method twice — once with the argument ‘Client’ to create the service’s OAuth2Client property, and again with the argument ‘Tokens’ to create a YouTube API object:</p><pre>&#39;use strict&#39;;</pre><pre>var YouTubeAPIService = require(&#39;./youtubeapiservice&#39;);<br>var youTubeAPIService = new YouTubeAPIService();</pre><pre>youTubeAPIService.initialize(&#39;Client&#39;);<br>youTubeAPIService.initialize(&#39;Tokens&#39;);</pre><p>When we run this module now, we’ll want to make sure to pass an additional environment variable — <strong>REFRESH_TOKEN</strong> — using the value you generated above with the getToken() method.</p><p>That’s pretty much it! In the .then() block of the second invocation of initialize, you can actually start using the YouTube API object — which is now fully authenticated — to query the YouTube Data API. Two of the utility methods we added to the prototype (generateAuthURL and getToken) only need to be used once, since the refresh token we generate never expires. The refreshAccessToken method can also be used outside of the context of initalize() whenever we want to refresh the token.</p><p>Here’s an example of how you can use the fully authenticated youTubeAPI object to access data from a private playlist associated with your Google account:</p><pre>&#39;use strict&#39;;</pre><pre>var YouTubeAPIService = require(&#39;./youtubeapiservice&#39;);<br>var youTubeAPIService = new YouTubeAPIService();</pre><pre>youTubeAPIService.initialize(&#39;Client&#39;);<br>youTubeAPIService.initialize(&#39;Tokens&#39;)<br>  .then(function(){<br>    youTubeAPIService.youtube.playlistItems.list({<br>      playlistId : &#39;dpYFG4qwrvU&amp;list=RDdpYFG4qwrvU&#39;,<br>      part : &#39;snippet&#39;,<br>      maxResults: &#39;50&#39;<br>    }, function(err, data){<br>      if(err){<br>        console.log(err);<br>        //do something to handle the error<br>        return err;<br>      }<br>      if(data){<br>        console.log(data);<br>        return data;<br>      }<br>    });<br>  });</pre><p>Have fun!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=46b4d430c6c5" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Using Node.js to Make MOZ API Requests]]></title>
            <link>https://medium.com/@mackplevine/using-node-js-to-make-moz-api-requests-496aba6ea01c?source=rss-cefb8c104c20------2</link>
            <guid isPermaLink="false">https://medium.com/p/496aba6ea01c</guid>
            <category><![CDATA[api]]></category>
            <category><![CDATA[nodejs]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[mozes]]></category>
            <category><![CDATA[seo]]></category>
            <dc:creator><![CDATA[Mackinley Levine]]></dc:creator>
            <pubDate>Sat, 03 Sep 2016 21:22:48 GMT</pubDate>
            <atom:updated>2016-09-04T00:57:50.108Z</atom:updated>
            <content:encoded><![CDATA[<p>If you’ve ever done any SEO work you may be familiar with MOZ, a third-party SEO data tool that is both user-friendly and highly regarded by the SEO community.</p><p>The Mozscape API gives customers with paid and unpaid accounts limited API access to MOZ’s metrics, making it a handy tool for pulling data on several URIs at once. MOZ hosts some helpful <a href="https://github.com/seomoz/SEOmozAPISamples">code samples</a> on GitHub but doesn’t yet include any demonstration of how to construct an API request in Node.js.</p><p>Here’s a code snippet that does essentially what the <a href="https://github.com/seomoz/SEOmozAPISamples/blob/master/php/batching_urls_sample.php">PHP example</a> does, but is written in Javascript and run in a Node.js environment:</p><pre>&#39;use strict&#39;;</pre><pre>var crypto = require(&#39;crypto&#39;);<br>var http = require(&#39;http&#39;);</pre><pre>// Set your expires times for several minutes into the future.<br>// An expires time excessively far in the future will not be honored by the Mozscape API.<br>// Divide the result of Date.now() by 1000 to make sure your result is in seconds.<br>var expires = Math.floor((Date.now() / 1000)) + 300;<br>var accessId = process.env.accessId;<br>var secretKey = process.env.secretKey;</pre><pre>// &#39;cols&#39; is the sum of the bit flags representing each field you want returned.<br>// Learn more here: <a href="https://moz.com/help/guides/moz-api/mozscape/api-reference/url-metrics">https://moz.com/help/guides/moz-api/mozscape/api-reference/url-metrics</a><br>var cols = &quot;68719476736&quot;;</pre><pre>// Put each parameter on a new line.<br>var stringToSign = accessId + &quot;\n&quot; + expires;</pre><pre>//create the hmac hash and Base64-encode it.<br>var signature = crypto.createHmac(&#39;sha1&#39;, secretKey).update(stringToSign).digest(&#39;base64&#39;);<br>//URL-encode the result of the above.<br>signature = encodeURIComponent(signature);</pre><pre>var postData = JSON.stringify([&#39;<a href="http://www.moz.com&/#39;">www.moz.com&#39;</a>, &#39;<a href="http://www.apple.com&/#39;">www.apple.com&#39;</a>, &#39;<a href="http://www.pizza.com&/#39;">www.pizza.com&#39;</a>]);</pre><pre>var options = {<br>  hostname: &#39;lsapi.seomoz.com&#39;,<br>  path: &#39;/linkscape/url-metrics/?Cols=&#39; + <br>   cols + &#39;&amp;AccessID=&#39; + accessId +<br>   &#39;&amp;Expires=&#39; + expires + &#39;&amp;Signature=&#39; + signature,<br>  method: &#39;POST&#39;,<br>  headers: {<br>    &#39;Content-Type&#39;: &#39;application/json&#39;,<br>    &#39;Content-Length&#39;: postData.length<br>  }<br>};</pre><pre>var responseData = &quot;&quot;;</pre><pre>var req = http.request(options, function(response){<br>  response.setEncoding(&#39;utf8&#39;);<br>  response.on(&#39;data&#39;, function(chunk){<br>    responseData += chunk;<br>  });<br>  response.on(&#39;end&#39;, function(){<br>   console.log(responseData);<br>  });<br>});</pre><pre>//Make the request.<br>req.write(postData);<br>req.end();</pre><p>You can really streamline the above code by installing and using the <a href="https://github.com/request/request">request</a> module in your project as opposed to using the native http service directly:</p><pre>&#39;use strict&#39;;</pre><pre>var crypto = require(&#39;crypto&#39;);<br>var request = require(&#39;request&#39;);</pre><pre>var expires = Math.floor((Date.now() / 1000)) + 300; //in seconds.<br>var accessId = process.env.accessId;<br>var secretKey = process.env.secretKey;</pre><pre>var stringToSign = accessId + &quot;\n&quot; + expires;<br>var cols = &#39;68719476736&#39;;<br>var signature = crypto.createHmac(&#39;sha1&#39;, secretKey).update(stringToSign).digest(&#39;base64&#39;);<br>signature = encodeURIComponent(signature);</pre><pre>var url =  &quot;<a href="http://lsapi.seomoz.com/linkscape/url-metrics/?Cols=">http://lsapi.seomoz.com/linkscape/url-metrics/?Cols=</a>&quot; + <br>   cols + &quot;&amp;AccessID=&quot; + accessId +<br>   &quot;&amp;Expires=&quot; + expires + &quot;&amp;Signature=&quot; + signature;</pre><pre>var postData = [&#39;<a href="http://www.moz.com&/#39;">www.moz.com&#39;</a>, &#39;<a href="http://www.apple.com&/#39;">www.apple.com&#39;</a>, &#39;<a href="http://www.pizza.com&/#39;">www.pizza.com&#39;</a>];</pre><pre>request({<br>  url :  url,<br>  method : &#39;POST&#39;,<br>  json : true,<br>  body : postData<br> }, function(err, response){<br>  if(err){<br>   console.log(err);<br>  } else {<br>   console.log(response.body);<br>  }<br> });</pre><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=496aba6ea01c" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Using ActiveMQ with Node.js, STOMP, and HTTP]]></title>
            <link>https://medium.com/@mackplevine/using-activemq-with-node-js-stomp-and-http-b251ce8d995?source=rss-cefb8c104c20------2</link>
            <guid isPermaLink="false">https://medium.com/p/b251ce8d995</guid>
            <category><![CDATA[activemq]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[nodejs]]></category>
            <dc:creator><![CDATA[Mackinley Levine]]></dc:creator>
            <pubDate>Mon, 29 Feb 2016 02:52:27 GMT</pubDate>
            <atom:updated>2016-03-30T16:54:56.570Z</atom:updated>
            <content:encoded><![CDATA[<p>ActiveMQ is written in Java and has a full-fledged JMS client, but its STOMP support and RESTful API let us interface with the messaging queue quite nicely using Node.js.</p><p>With Node, you’ll find that STOMP is a great choice of protocol for subscribing to queues, while HTTP is ideal for sending messages (and is particularly great for messages that are scheduled to be delivered at a set time due to the info-rich response we receive from the queue upon scheduling a message for delivery).</p><p>Let’s start with the basics. Using <a href="https://github.com/russellhaering">Russel Haering</a> and <a href="https://github.com/easternbloc">easternbloc</a>’s very handy <a href="https://github.com/easternbloc/node-stomp-client">node-stomp-client</a>, we can create a class in Node.js that allows us to subscribe to the ActiveMQ queue of our choice. Here’s how this might look:</p><pre>&#39;use strict&#39;;</pre><pre>var Stomp = require(&#39;stomp-client&#39;);</pre><pre>var MessageConsumer = function MessageConsumer(){};</pre><pre>MessageConsumer.prototype.init = function init(){<br>  var stompClient = new Stomp(&#39;127.0.0.1&#39;, 61613, &#39;user&#39;, &#39;pw&#39;);<br>  stompClient.connect(function(sessionId){<br>    stompClient.subscribe(&#39;/queue/queue1&#39;, function(body, headers){<br>      /*<br>      this callback function is invoked whenever our a client receives a message.<br>      */<br>    }<br>  });<br>};</pre><pre>module.exports = new MessageConsumer();</pre><p>Just call the init() method on this class to subscribe to a queue. (It’s also worth mentioning here that the way we refer to queues in STOMP is different than how we would do so with JMS — with STOMP, we need to prepend the string ‘/queue/’ to the name of the queue itself.)</p><p>Posting a message with STOMP is easy. Let’s create a class that can be used to send a message below:</p><pre>&#39;use strict&#39;;<br>var Stomp = require(‘stomp-client’);</pre><pre>var MessageProducer = function MessageProducer(){<br>  this._stompClient = null;<br>};</pre><pre>MessageProducer.prototype.init = function init(){<br>  this._stompClient = new Stomp(‘127.0.0.1’, 61613, ‘user’, ‘pw’);<br>  this._stompClient.connect(function(sessionId){<br>    console.log(“STOMP client connected.”);<br>  });<br>};</pre><pre>MessageProducer.prototype.sendMessage = function sendMessage(messageToPublish){<br>  this._stompClient.publish(&#39;/queue/queue1&#39;, messageToPublish);<br>};</pre><pre>module.exports = new MessageProducer();</pre><p>You might notice a major limitation of the approach for publishing messages used above — there’s no way to verify receipt of the message from the broker! STOMP 1.2 does give us something called a ‘receipt’ frame (here’s a <a href="https://github.com/gdaws/node-stomp">Node.js client</a> that implements it), and while it helps us timing-wise with processes that must occur after a message has been sent to the broker and are contingent upon successful receipt of the message by that broker (say, for instance, you want to write a record of that message to a database somewhere), it doesn’t send back any detailed data having to do with the message itself.</p><p>Imagine a scenario where you schedule a message for future delivery, but need some mechanism that would allow you to cancel delivery of that message (ActiveMQ does have a nifty scheduler, which you can read about <a href="http://activemq.apache.org/delay-and-schedule-message-delivery.html">here</a>). The problem is that <strong>you can only delete individual messages using the internal message ID that ActiveMQ’s message scheduler generates, </strong>and STOMP gives you no way to retrieve this ID immediately after scheduling a message.</p><p>It’s still possible to delete a scheduled message using STOMP. Here’s what you’d need to do (there are quite a few hoops to jump through, but what I’m about to do is the same basic method described <a href="http://timbish.blogspot.com/2010/10/enhanced-jms-scheduler-in-activemq.html">here</a> but with an external Node.js client as opposed to JMS):</p><ul><li>First, make sure to send along some other kind of identifying information with the headers for the message we publish. For example, can use ActiveMQ’s correlation-id property and give it a value of a UUID that can function as the primary key for the record of the scheduled message we save to a database. To accomplish this, you can modify the sendMessage method on your MessageProducer class to look like the following:</li></ul><pre>MessageProducer.prototype.sendScheduledMessage = function sendScheduledMessage(messageToPublish, scheduledTime, correlationId){<br>  this._stompClient.publish(&#39;/queue/queue1&#39;, messageToPublish, {<br>    AMQ_SCHEDULED_DELAY : scheduledTime,<br>    correlation-id : correlationId<br>  });<br>};</pre><ul><li>Once ActiveMQ has a few scheduled messages queued up for timed delivery, send a message that initiates a “browse” request. To do this, you’ll need to use your MessageProducer class’s internal STOMP client to publish a message to the ActiveMQ.Scheduler.Management topic (so the first argument you’ll pass to stompClient.subscribe is this string: “/topic/ActiveMQ.Scheduler.Management”). The message you send to initiate a browse must include the following headers:</li></ul><pre>{<br>reply-to: &quot;/queue/browsedMessages&quot;,<br>AMQ_SCHEDULER_ACTION: &quot;AMQ_SCHEDULER_ACTION_BROWSE&quot;<br>}</pre><p>(Note: the queue ‘browsedMessages’ can be called anything — you’re just creating a queue that will receive copies of any message currently in ActiveMQ’s scheduler.)</p><ul><li>Next, create another STOMP client and subscribe it to this ‘browsedMessages’ queue. It will consume all of the messages that end up in the browsedMessages queue, and once it consumes that copy of the message you want to delete (you verify the ID of the message you want to delete by inspecting the headers for the correlation-id you sent along with the message when it was scheduled), take its corresponding ‘message-id’ property (you’ll also find this in the response headers) and send this along as the value for “scheduledJobId” in the headers of a new message to ActiveMQ, which will be used to <strong>delete</strong> the desired message from the scheduler. Here’s what the headers for this subsequent request will look like:</li></ul><pre>{<br>AMQ_SCHEDULER_ACTION : &quot;REMOVE&quot;,<br>&quot;scheduledJobId&quot; : scheduledJobId<br>}</pre><ul><li>The example code below should extend your MessageProducer class with methods that will allow you to pull this off:</li></ul><pre>MessageProducer.prototype._sendDeleteMessageRequest = function _sendDeleteMessageRequest(scheduledJobId){<br>  this._stompClient.publish(“/topic/ActiveMQ.Scheduler.Management”, null, {<br>    AMQ_SCHEDULER_ACTION : “REMOVE”,<br>    “scheduledJobId” : scheduledJobId<br>  });<br>};</pre><pre>MessageProducer.prototype._sendBrowseRequest = function _sendBrowseRequest(){<br>  this._stompClient.publish(“/topic/ActiveMQ.Scheduler.Management”, null, {<br>    “reply-to” : “/queue/browsedMessages”,<br>    AMQ_SCHEDULER_ACTION : “AMQ_SCHEDULER_ACTION_BROWSE”<br>  });<br>};</pre><pre>MessageProducer.prototype.deleteMessage = function deleteMessage(correlationId){<br>  var browserConsumer = new Stomp(‘127.0.0.1’, 61613, ‘user’, ‘pw’);<br>  var self = this;<br>  return new Promise(function(resolve, reject){<br>    browserConsumer.connect(function(sessionId){<br>    browserConsumer.subscribe(destination, function(body, headers) {<br>      if (headers[‘correlation-id’] === correlationId){<br>        browserConsumer.disconnect(function(){<br>          return resolve(headers[‘message-id’]);<br>        });<br>      }<br>    });<br>    process.nextTick(function(){<br>      self._sendBrowseRequest();<br>    });<br>  });<br>}).then(function(headers){<br>  self._sendDeleteMessageRequest(headers.scheduledJobId);<br>  });<br>};</pre><p>If this whole process struck you as a huge, suboptimal pain in the ass, don’t worry — there’s hope.</p><h4>Scheduling and deleting with HTTP &amp; REST</h4><p>Here’s a really easy, promisified way to use HTTP to schedule a message, assuming you have <a href="http://activemq.apache.org/rest.html">ActiveMQ’s REST API</a> enabled:</p><pre>&#39;use strict&#39;;</pre><pre>var request = require(&#39;request&#39;);<br>var Promise = require(&#39;bluebird&#39;);</pre><pre>var MessageScheduler = function MessageScheduler(){};</pre><pre>MessageScheduler.prototype.scheduleMessage = function scheduleMessage(messageToSend, delay){<br>  var promisifiedPostRequest = Promise.promisify(request.post);<br>  return promisifiedPostRequest(<br>    &#39;http://localhost:8080/demo/message/queue1?type=queue&#39;, <br>    {<br>      form : {<br>        body: JSON.stringify(notification),<br>        AMQ_SCHEDULED_DELAY : delay<br>    }<br>  })<br>  .then(function(response){<br>    return response.headers.messageid;<br>  });<br>};</pre><p>See that bit in the .then() block? This is where we can get access to the message ID that ActiveMQ assigns to the scheduled message which, incidentally, <strong>has the same value as the message’s scheduledJobId.</strong></p><p>That’s the beauty of HTTP: it gives us access to this very important property in the response of the request, which means we don’t have to issue a ‘browse’ request to dig it up later.</p><p>Now that we have this value, using it to delete the scheduled message it identifies is easy:</p><pre>&#39;use strict&#39;;</pre><pre>var Promise = require(&#39;bluebird&#39;);<br>var request = require(&#39;request&#39;);</pre><pre>var MessageDeleter = function MessageDeleter(messageID){<br>  var promisifiedPostRequest = Promise.promisify(request.post);<br>  return promisifiedPostRequest(<br>  &#39;http://localhost:8080/demo/message/ActiveMQ.Scheduler.Management?type=topic&#39;, <br>  {<br>    form: {<br>      AMQ_SCHEDULER_ACTION : &#39;REMOVE&#39;,<br>      scheduledJobId : scheduledJobId<br>    }<br>  }).then(function(response){<br>    //do any post-deletion processes you need to here<br>    return response;<br>  }<br>}</pre><p>With REST, that’s all there is to it.</p><p>The only major limitation to deleting messages (and this is true for both STOMP and HTTP) is the fact that we do not receive confirmation from ActiveMQ that the message was in fact deleted — just that the <em>request </em>to delete this message was received and processed. The message targeted for deletion may have even been delivered to a consumer before the message containing the delete request even reached the queue.</p><p>Regardless, this gets us a whole lot closer to having a reliable, quick, Node-based means of interfacing with ActiveMQ’s message scheduling capabilities.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b251ce8d995" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Node.js Module Caching]]></title>
            <link>https://medium.com/@mackplevine/node-js-module-caching-10c4e395423e?source=rss-cefb8c104c20------2</link>
            <guid isPermaLink="false">https://medium.com/p/10c4e395423e</guid>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[nodejs]]></category>
            <dc:creator><![CDATA[Mackinley Levine]]></dc:creator>
            <pubDate>Mon, 02 Nov 2015 15:30:57 GMT</pubDate>
            <atom:updated>2015-11-02T15:30:57.150Z</atom:updated>
            <content:encoded><![CDATA[<p>Let’s have a look at the following three snippets of code. Here’s a basic express server:</p><pre>var express = require(‘express’);<br>var http = require(‘http’);<br>var app = express();</pre><pre>var module1 = require(‘./module1’);<br>var module2 = require(‘./module2’);</pre><pre>http.createServer(app).listen(8000, function() {<br>  console.log(‘Server listening on port ‘ + 8000);<br>  module1.init();<br>  module2.test();<br>});</pre><p>As you can see, I’ve required two modules on lines 5 and 6 (using variables module1 and module2). Here’s module1:</p><pre>var ModuleObject1 = function(){<br>  this.attribute1 = null;<br>  this.attribute2 = null;<br>}</pre><pre>ModuleObject1.prototype.init = function(){<br>  this.attribute1 = “initiated!”;<br>  this.attribute2 = “also initiated”;<br>}</pre><pre>module.exports = new ModuleObject1();</pre><p>All module1 really does is instantiate an object with some null properties when required in other modules. The ‘init’ method gives these properties values, but before this method is invoked, these properties remain null.</p><p>Now have a look at module2:</p><pre>var module1 = require(‘./module1’);</pre><pre>var ModuleObject2 = function(){};</pre><pre>ModuleObject2.prototype.test = function(){<br>  if (module1.attribute1 !== null &amp;&amp; module1.attribute2 !== null){<br>    console.log(“server-induced changes to module1 persist in the cache!”);<br>  }<br>}</pre><pre>module.exports = new ModuleObject2();</pre><p>module1 is required in this module, but has not yet been initialized.</p><p>Here’s where things get interesting. Run server.js, and you should see the module2’s test() method pass and log something to the console, meaning that the object the module1 variable is pointing to had properties with values. But its init() method was never called within the scope of module2!</p><p>It would make sense to assume that the require statements in both server.js and module2.js create different instances of an object, <em>but they don’t</em>. The module gets <strong>cached </strong>during the first require statement, meaning only one instance of that object is created — subsequent require statements in other modules just enable us to access that same object. That’s why changes we made to the object in server.js persist when we access the object in module2 — both server.js and module2 really just access the same object.</p><p>We can break this functionality pretty easily by moving the ‘new’ keyword, enabling us to instantiate different objects that are accessible in different scopes. Let’s try it.</p><p>Here’s the new server.js:</p><pre>var express = require(‘express’);<br>var http = require(‘http’);<br>var app = express();</pre><pre>var module1constructor = require(‘./module1’);<br>var module1 = new module1constructor();<br>var module2 = require(‘./module2’);</pre><pre>http.createServer(app).listen(8000, function() {<br>  console.log(‘Server listening on port ‘ + 8000);<br>  module1.init();<br>  module2.test();<br>});</pre><p>Here’s the new module1:</p><pre>var ModuleObject1 = function(){<br>  this.attribute1 = null;<br>  this.attribute2 = null;<br>}</pre><pre>ModuleObject1.prototype.init = function(){<br>  this.attribute1 = “initiated!”;<br>  this.attribute2 = “also initiated”;<br>}</pre><pre>module.exports = ModuleObject1;</pre><p>And here’s the new module2:</p><pre>var module1constructor = require(‘./module1’);<br>var module1 = new module1constructor();</pre><pre>var ModuleObject2 = function(){};</pre><pre>ModuleObject2.prototype.test = function(){<br>  if (module1.attribute1 !== null &amp;&amp; module1.attribute2 !== null){<br>  console.log(“server-induced changes to module1 persist in the cache!”);<br>  }<br>}</pre><pre>module.exports = new ModuleObject2();</pre><p>Run server.js. This time, you should notice that nothing is printed to the console.</p><p>Let’s take a look at how this works. module1 does indeed get its properties assigned string values because we invoked its init() method — but the module1 variable now points to a distinct object that is only accessible within the scope of server.js. The same is true of module2; it’s no longer accessing a cached object: it’s now accessing an <em>instance</em> of an object class within its own scope. We’re still caching something, though — we’re caching the <strong>constructor function</strong> as opposed to the <strong>object. </strong>You’d still be able to log a string to the console by invoking the attribute1 and attribute2 properties of module1, but module2.init() interfaces with a different object that has not yet had its init() method invoked.</p><p>This caching functionality might have major implications for your project, so try to get comfortable with how it works!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=10c4e395423e" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Node.js get-pixels: Getting Pixels at Specific Sectors of an Image using ndarray]]></title>
            <link>https://medium.com/@mackplevine/node-js-get-pixels-getting-pixels-at-specific-sectors-of-an-image-using-ndarray-e6d4cb285d36?source=rss-cefb8c104c20------2</link>
            <guid isPermaLink="false">https://medium.com/p/e6d4cb285d36</guid>
            <category><![CDATA[npm]]></category>
            <category><![CDATA[nodejs]]></category>
            <category><![CDATA[javascript]]></category>
            <dc:creator><![CDATA[Mackinley Levine]]></dc:creator>
            <pubDate>Thu, 17 Sep 2015 04:26:45 GMT</pubDate>
            <atom:updated>2015-09-17T04:26:45.487Z</atom:updated>
            <content:encoded><![CDATA[<p><a href="https://www.npmjs.com/"><strong>npm</strong></a> has a <a href="https://www.npmjs.com/package/get-pixels">handy package</a> for extracting pixel data from a given image, but it doesn’t give us any (obvious) way to extract pixels from a given sector of the image with a defined width and height. Doing this on the client side is easy, since we have tools like HTML5&#39;s canvas element, but server side, we’re kind of stuck.</p><p>Let’s take a look at how we can implement the math to do this on a node.js server, given an image with a certain width and height and assuming we don’t have something like canvas to abstract this away for us.</p><p>First, let’s set up our module to require get-pixels:</p><pre>var getPixels = require(‘get-pixels’);</pre><p>Next, we’ll build out a function that can invoke getPixels on a given image. For the sake of illustration, let’s imagine that the property req.body.imagePath contained the path to our image:</p><pre>var pixelGetter = function(req, res){<br>  getPixels(req.body.imagePath, function(err, pixels){<br>    if (err){<br>      console.log(err);<br>      return;<br>    } else {<br>      console.log(pixels.data);<br>    }<br>  });<br>}</pre><p>pixels.data returns a buffer object with a length property, and we can iterate over it similar to how we’d iterate over the indices of an array. The first four indices will be RGBA values, respectively, for the first pixel; the second four indices will be RGBA values for the second pixel, and so on. Here’s what this might look like:</p><pre>[255, 255, 235, 0, 253, 143, 32, 0…]</pre><p>Imagine we had a .png image with a width of 5 pixels and height of 5 pixels. When getPixels is invoked on this image, it would return a buffer object with 100 elements: 5 pixels by 5 pixels is 25 pixels total, each with an R component, a G component, a B component, and an A component — 25 pixels with 4 properties each gives us 100 total elements.</p><p>Our problem is that when accessed on pixels.data, all of these elements exist in a totally flat array! Fortunately, iterating through the array stored on the .data property isn’t the only way for us to access pixels in the image, since get-pixels actually returns a <a href="https://github.com/scijs/ndarray"><strong>ndarray</strong></a><strong>. </strong>‘n,’ in this case, refers to the number of dimensions the array has — ours has 3, and might look something like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/599/1*Jeqi8D9A9L9nUzUTdz3Gkw.png" /></figure><p>Think of the red, blue, green and gray squares as representing the RGBA values for a given pixel, and that data for a given pixel is four elements “deep.”</p><p>Now, assume we had an ndarray representing image that was 5 pixels by 5 pixels (like the visual representation of the ndarray to the left) and simply wanted pixels for the the top-left 3px by 3px segment of the image. This isn’t too hard to accomplish using a couple of nested for loops:</p><pre>var flatArray = [];<br>for (var y = 0; y &lt; 3; i++){<br>  for (var x = 0; x &lt; 3; j++){<br>    for (var z = 0; z &lt; 4; k++){<br>      flatArray.push(pixels.get(x, y, z));<br>    }<br>  }<br>}</pre><p>Let’s have a look at everything we’ve done in the chunk of code above, starting with the code contained in the innermost for loop.</p><p>pixels.get takes as many arguments as there are dimensions, and these appear in the order we’d expect them to — in our case, we have <strong>x </strong>for width, <strong>y </strong>for height, and <strong>z </strong>for “depth.” (With animated gifs, there’s even a fourth dimension, representing pixels at each frame. That’s right — time!) Dimension <strong>z </strong>can be understood metaphorically as “depth” — and it makes sense if you think of each pixel as 4 elements deep due to it having an r, g, b and a value, respectivley. Here’s our image again:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/599/1*Jeqi8D9A9L9nUzUTdz3Gkw.png" /></figure><p>Our iteration starts at the red square in the top-left of the cube — we traverse across the red face of our cube, left-to-right, top-to-bottom, and at each stop on a red square, we dive inward and grab the red, green, blue, and alpha values for the pixel. When constructing a flat array, we want to push each of these r, g, b and a values (whatever they may be) to the to the array before moving on to the pixel to its right (this happens as we iterate through the <strong>x </strong>loop). And of course, once we’ve reached the 5th pixel in a horizontal row of pixels (x=4), we increment y once to move to the row immediately below it, reset x to zero, and repeat.</p><p>If we wanted to get a 3x13 chunk of pixels in the top-right quadrant of our image, our code would look really similar:</p><pre>var flatArray = [];<br>for (var y = 2; i &lt; 5; i++){<br>  for (var x = 2; j &lt; 5; j++){<br>    for (var z = 0; k &lt; 4; k++){<br>      flatArray.push(pixels.get(x, y, z));<br>    }<br>  }<br>}</pre><p>In either case, our variable flatArray will end up looking something like this:</p><pre>[235, 216, 130, 0, 253, 143, 32, 0…]</pre><p>Turning this back into an ndarray is trivial. First, install ndarray using npm:</p><pre>npm install ndarray</pre><p>Now require it in your node module so we can get access to all of its nifty methods:</p><pre>var ndarray = require(‘ndarray’);</pre><p>Creating an ndarray with our desired dimensions is as easy as invoking the following on our variable flatArray:</p><pre>var pixelArray = ndarray(new Float64Array(flatArray), [10,10,4])</pre><p>Now, we have an ndarray that lets us access the rgba values of pixels using the handy getter and setter methods that come bundled with the module.</p><p>Here’s a twist, though — the above is nice for knowing what’s going on under the hood, but it turns out that <strong>ndarrays have methods that allow for us to abstract a lot of this math away.</strong></p><p>We can actually slice this array in three dimensions using <a href="https://github.com/scijs/ndarray#slicing"><strong>.hi </strong>and <strong>.lo.</strong></a><strong> </strong>Think of .lo as clicking and dragging the upper-left corner of our image towards the bottom right of the image to grab some pixels. Using the 5x5 pixel model illustrated above, we could grab the R values for the top-left 3x3 corner of our image by invoking this (remember, arrays in JavaScript are zero-based):</p><pre>pixelArray.lo(2, 2, 0);</pre><p>The resulting selection would be an ndarray that looked like the orange segment of our model below:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/891/1*ue6a_-hBQPrwYvUZcdkFcg.png" /></figure><p>We can chain .lo with .hi to select only the portion produced by the overlap of each method. If we wanted only the R value of of the pixel located at (2, 2), we could write code that looked like this:</p><pre>pixelArray.lo(2, 2, 0).hi(2, 2, 0);</pre><p>Here’s what the selection looks like on our model, with the overlapping portion colored in a darker shade of orange and with the non-overlapping portions of the chained selections stripped away, respectively:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/915/1*BeX-IVGDKvKZrJpJuuWUcw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/878/1*1SWp_ECgHin6hei9aeKc4g.png" /></figure><p>While it serves for a nice illustration of how these methods function, using chained .lo and .hi methods wasn’t really necessary to grab this pixel, since all we’d really have to is write the following code:</p><pre>pixelArray.get(2, 2, 0);</pre><p>There are plenty of cases where we’d want to use this method chaining, however.</p><p>Let’s say we wanted to select the bottom-left 2x2 sector of the image. Our code would look like this:</p><pre>pixelArray.lo(2, 4, 0).hi(4, 2, 0);</pre><p>Here’s what this would look like on our model:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/809/1*GQZTrL2eniTBQPgNcmMJlw.png" /></figure><p>We haven’t explored grabbing depth yet. If we wanted to grab both the red and the green portions of this 2x2 chunk of pixels, all we’d have to do is change our code to look like this:</p><pre>pixelArray.lo(2, 4, 1).hi(4, 2, 1);</pre><p>Again, here’s what that would look like on our model:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/841/1*cWWTLX4keUu26NmtwHWu5g.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/763/1*_MrMF4ktQNDP0WF_wJrXDQ.png" /></figure><p>That’s pretty much it! ndarrays are extremely handy for grabbing elements in a multi-dimensional array, and is especially handy for when we want to grab and perform analysis on certain pixels in an image.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e6d4cb285d36" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>