<?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 Jake Burden on Medium]]></title>
        <description><![CDATA[Stories by Jake Burden on Medium]]></description>
        <link>https://medium.com/@Jekrb?source=rss-ad55bb067148------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*aBKAiuXJVb7TOY0uVZRnPA.jpeg</url>
            <title>Stories by Jake Burden on Medium</title>
            <link>https://medium.com/@Jekrb?source=rss-ad55bb067148------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 30 Nov 2026 13:42:52 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@Jekrb/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[Shopify Store Duplication]]></title>
            <link>https://medium.com/digital-surgeons-engineering/shopify-store-duplication-9727b7b2978a?source=rss-ad55bb067148------2</link>
            <guid isPermaLink="false">https://medium.com/p/9727b7b2978a</guid>
            <category><![CDATA[duplication]]></category>
            <category><![CDATA[shopify]]></category>
            <category><![CDATA[apps]]></category>
            <category><![CDATA[development]]></category>
            <category><![CDATA[nodejs]]></category>
            <dc:creator><![CDATA[Jake Burden]]></dc:creator>
            <pubDate>Fri, 19 Apr 2019 03:09:59 GMT</pubDate>
            <atom:updated>2021-03-22T14:21:40.557Z</atom:updated>
            <content:encoded><![CDATA[<h4>Open Source Tools to Copy Pages and Products</h4><p><strong>Background</strong></p><p>Shopify developers may find themselves needing to create duplicate versions of their live store. They might want to create a “playground” or “dev” store to test some changes before releasing new designs and features to the world. Or they might be migrating a large, global brand to Shopify and want all the international stores to follow a consistent brand aesthetic. There is a range of reasons for creating duplicate stores. However, Shopify as a platform does not make this easy to accomplish on your own.</p><p><strong>Problem</strong></p><p>The two most prevalent avenues to take when it comes to store duplication are not that appealing to developers. The first way to accomplish store duplication is to install a Shopify app, but you’ll be paying for the duplication process. The second method is to politely ask Shopify support to help. They have been really great for us in the past!</p><p>Also a secondary issue: It is possible to export product data from the Shopify dashboard, and import the data in your target store. But the export gets sent to the store owner via email. If you’re just the developer and not the store owner, you’ll need to ping the owner to forward you that email!</p><p><strong>Solution</strong></p><p>Around a year ago we published a couple of open source tools to try to make Shopify store duplication easier. Let’s show how to use <a href="https://github.com/jekrb/shopify-cp">shopify-cp</a> (where cp is pronounced “copy”, like the UNIX command), the tool that copies all products and pages from a source store to a destination store in one go.</p><p>First thing you’ll want to do is create private app on both the source and destination store (your duplicate store). You’ll need the API credentials that Shopify generates. It will look like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*9pqtJZ3ODjdY8o4FvSXIUw.png" /></figure><p>Once you have two private apps created, one for each store, it’s time to get your duplication script ready.</p><p>I mentioned <a href="https://github.com/jekrb/shopify-cp">shopify-cp</a> above, which is actually a utility module that is currently a collection of two other modules, <a href="https://github.com/jekrb/shopify-pages-cp">shopify-pages-cp</a> and <a href="https://github.com/jekrb/shopify-products-cp">shopify-products-cp</a>.</p><p>Start by npm installing shopify-cp to your project directory.</p><pre>npm i shopify-cp</pre><p>Next, you should be able to copy the following script into a JavaScript file, using it mostly as is except swapping the values for source and sink with the credentials from your private apps.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/3ab6eb56af272b0b10d86ed0d653e70e/href">https://medium.com/media/3ab6eb56af272b0b10d86ed0d653e70e/href</a></iframe><p>Then run the script with Node.js:</p><pre>node shopify-cp-usage.js</pre><p>You should then see a lot of JSON output of all the pages and products that are being duplicated over. When the JSON output stops streaming, that means the task is done and the program will end itself.</p><p>If you would rather not see any output in the terminal, simply omit the .pipe(process.stdout) on line 9.</p><p>Also, if you are only looking to duplicate pages, or only products, but not both, you can use the <a href="https://github.com/jekrb/shopify-pages-cp">shopify-pages-cp</a> and <a href="https://github.com/jekrb/shopify-products-cp">shopify-products-cp</a> modules individually. The API for these are both the same:</p><pre>cp(source, sink)</pre><p>This API returns a stream actually, so all the responses we get back from Shopify can be piped to another program or file:</p><pre>cp(source, sink).pipe(process.stdout)</pre><p>I would be happy to explain how these modules work, particularly the streaming aspect of them in conjunction with the Shopify API, but that can be its own article which I will likely try to write in the near future.</p><p>In the meantime, these are all open source so you can check out what they are doing under the hood and also verify that we aren’t sending your private app credentials anywhere:</p><ul><li><a href="https://github.com/jekrb/shopify-cp">jekrb/shopify-cp</a></li><li><a href="https://github.com/jekrb/shopify-pages-cp">jekrb/shopify-pages-cp</a></li><li><a href="https://github.com/jekrb/shopify-products-cp">jekrb/shopify-products-cp</a></li></ul><blockquote>Is shopify-cp any good?</blockquote><p>While <strong>these tools only help with duplicating products and pages</strong>, we’ve found that this has been all we needed for the majority of cases. We’ve also been using these tools for nearly a year now and have not found any bugs or issues so far.</p><p>If we needed to get into duplicating collections and metafields, chances were that we likely needed to work with Shopify support to request some internal expansion tooling.</p><p>These tools have really been a time saver for the Shopify sites we build at <a href="https://www.digitalsurgeons.com/?utm_source=medium&amp;utm_medium=jake&amp;utm_campaign=shopifymultiplication">Digital Surgeons</a>, and I’m happy to be formally talking about them here.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9727b7b2978a" width="1" height="1" alt=""><hr><p><a href="https://medium.com/digital-surgeons-engineering/shopify-store-duplication-9727b7b2978a">Shopify Store Duplication</a> was originally published in <a href="https://medium.com/digital-surgeons-engineering">Digital Surgeons Engineering</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to set up a local development environment for serverless Next.js]]></title>
            <link>https://medium.com/digital-surgeons-engineering/how-to-set-up-a-local-development-environment-for-serverless-next-js-5dfe7e1f663d?source=rss-ad55bb067148------2</link>
            <guid isPermaLink="false">https://medium.com/p/5dfe7e1f663d</guid>
            <category><![CDATA[nextjs]]></category>
            <category><![CDATA[local-development]]></category>
            <category><![CDATA[serverless]]></category>
            <category><![CDATA[now]]></category>
            <category><![CDATA[zeit]]></category>
            <dc:creator><![CDATA[Jake Burden]]></dc:creator>
            <pubDate>Mon, 11 Feb 2019 01:50:03 GMT</pubDate>
            <atom:updated>2019-02-11T02:37:40.814Z</atom:updated>
            <content:encoded><![CDATA[<h3>How to set up a local development environment for serverless Next.js apps on Now v2 with Node.js lambda functions</h3><p>The latest version of <a href="https://now sh">now</a> enables users to deploy serverless applications and lambda functions with ease. If you’ve had the opportunity to try this out, you’ll probably find that Now v2 makes your deployments feel impressive.</p><p>Splitting your app into individual lambda functions makes cold start time nearly unnoticeable. It forces you to make good decisions with dependencies and data storage. Also, you can write each lambda function for your app in the best language for <em>that particular endpoint</em>. You can pick from a range of languages such as JavaScript, PHP, Go, Python, Bash, and even Rust. But there’s always one question that new users ask.</p><blockquote>What is the local development story?</blockquote><p>The Zeit team is working hard on a new local development tool called <a href="https://github.com/zeit/now-cli/commits/now-dev"><em>now dev</em></a> which by the look of the commits coming in, will be released soon (a few days to a couple of weeks is my guess). We are anticipating that now dev will let you run your entire serverless project locally, so you can build and debug without needing to do any deployments.</p><p>So what should you do in the meantime? I don’t have a complete answer for the full range of what now deployments offer, but I will show you how I’ve been building my serverless Next.js apps with Node.js lambda functions locally.</p><h3>Routing, Builds, and now.json</h3><p>Ensure that you’ve configured a now.json. Here is an example of one that I’m currently using. It uses the @now/next builder for the app found in my package.json, and the@now/node builder for any JavaScript file in my /api directory. For my routes, any call to an endpoint starting with/api/ gets forwarded to the respective file in that directory. Any call to a URL such as /apply/&lt;job url&gt; gets forward to Next.js as /appy?job=&lt;job url&gt; in the /www directory (which is where the app lives). Any other URL is handled normally via Next.js.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c5964e16084fd7b4d8ca8699edf84216/href">https://medium.com/media/c5964e16084fd7b4d8ca8699edf84216/href</a></iframe><h3>Running Node.js Lambda Functions Locally</h3><p>You’ll want to globally install <a href="https://github.com/krasimir/now-lambda-runner">now-lambda-runner</a> , which is a tool that reads your now.json, then it creates a Node.js server and makes your lambda functions over localhost.</p><pre>npm i now-lambda-runner -g</pre><p>For example, if you’ve created a jobs.js lambda function in a /api directory and your API routes are structured the same way mine are above, this will be the localhost URL for your API:</p><pre><a href="http://localhost:8004/api/jobs.js">http://localhost:8004/api/jobs.js</a></pre><p>If you want your lambda functions to be available locally, open your terminal to the root of your project (or wherever your now.json is) and run:</p><pre>now-lambda</pre><p>If your now.json looks like mine, you’ll see something like this:</p><pre>~/example-app ∴ now-lambda<br>-----------------------------------<br>Routes:<br> ALL - <a href="http://localhost:8004/api/(.*)">http://localhost:8004/api/(.*)</a><br> ALL - <a href="http://localhost:8004/apply/(?">http://localhost:8004/apply/(?</a>&lt;job&gt;[^/]+)$<br> ALL - <a href="http://localhost:8004/(.*)">http://localhost:8004/(.*)</a><br>-----------------------------------</pre><h3>Running Next.js locally</h3><p>This part is easy. In another terminal tab, go to the root of your Next.js app and enter the command npm run dev. If you follow the now.json structure above then it will look like this:</p><pre>~ ∴ cd example-app/www/<br>~/example-app/www ∴ npm run dev</pre><h3>Page.getInitialProps and absolute URLs</h3><p>Your Next.js app is now running on localhost:3000and your lambda functions are running on localhost:8004.</p><p>You can server-side render your app with information from your APIs by calling them within Page.getInitialProps and returning the data to be used as props from your Page component.</p><p>Let’s look at the following Page.getInitalProps as an example of how you might try to call your API and <strong>the problems that you’ll run into which we’ll fix afterward</strong>:</p><pre>// ❌ localhost:8004 won&#39;t work on live deployments</pre><pre>Page<em>.</em>getInitialProps = <em>async</em> () =&gt; {<br>  const<em> jobs </em>=<em> await </em>(<br>    <em>await </em>fetch(`http://localhost:8004<em>/api/allJobs.js</em>`)<br>  )<em>.</em>json()<br><em>  return</em> {<br>    jobs<br>  }<br>}</pre><p>This will run locally, but if you deploy this with now it will not work since your deployed app will not be running on localhost:8004 . So what about using relative URLs instead? (<strong>Hint: this will not work either</strong>)</p><pre>// ❌ `now` deployments require absolute urls</pre><pre>Page<em>.</em>getInitialProps = <em>async</em> () =&gt; {<br>  const<em> jobs </em>=<em> await </em>(<br>    <em>await </em>fetch(&#39;<em>/api/allJobs.js&#39;</em>)<br>  )<em>.</em>json()<br><em>  return</em> {<br>    jobs<br>  }<br>}</pre><p>If you try to load this page on a now deployment, you’ll be greeted with an error:</p><pre>Error: only absolute urls are supported</pre><p>So you need some way to determine the full absolute URL, both locally and on a live deployment. Also since now uses unique, immutable URLs for deployments before you alias to a domain, you can not deterministically hardcode a deployment URL ahead of time.</p><p><strong>Here is one working way to get around that</strong>:</p><pre>// ✅ URL generated from the host environment and works with local development setup.</pre><pre>Page<em>.</em>getInitialProps = <em>async</em> ({ req }) =&gt; {<br>  let<em> </em>protocol<em> </em>=<em> </em>&#39;https:&#39;<br>  let<em> </em>host<em> </em>=<em> </em>req<em> </em>?<em> </em>req<em>.headers.host </em>:<em> window.location.hostname<br>  </em>if (host<em>.</em>indexOf(&#39;localhost&#39;) &gt; -1) {<br>    host = &#39;localhost:8004&#39;<br>    protocol = &#39;http:&#39;<br>  }</pre><pre>  const<em> jobs </em>=<em> await </em>(<br>    <em>await </em>fetch(`${protocol}<em>//</em>${host}<em>/api/allJobs.js</em>`)<br>  )<em>.</em>json()</pre><pre><em>  return</em> {<br>    jobs<br>  }<br>}</pre><p>So what is going on with this line here?<br>let<em> </em>host<em> </em>=<em> </em>req<em> </em>?<em> </em>req<em>.headers.host </em>:<em> window.location.hostname</em></p><p>There we are checking for a req object. If it exists then Page.getInitialProps is running on the server, and we can get the hostname with req.header.host. However, if we have navigated to this page via next/link, then Page.getInitialProps is running on the client side, which means we have to get the hostname from window.location.hostname. If our hostname happens to contain localhost, then it’s probably running locally and is not a deployment URL, and in this case, we are setting the host to localhost:8004.</p><p>That is a bit much to remember and copy/paste on every page that makes API calls in getInitialProps, so I made a module to make this a bit easier.</p><p>Inside the directory of your Next.js app ( /www in my case) run the following command to install <a href="https://github.com/jekrb/next-absolute-url">next-absolute-url</a>, a module that abstracts all the checking above.</p><pre>npm i next-absolute-url</pre><p>✅ Then you can use it in your Next.js app. <strong>Feel free to copy this</strong>:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/1c39a8b78a321ce2a14b522d821a2980/href">https://medium.com/media/1c39a8b78a321ce2a14b522d821a2980/href</a></iframe><p>The second argument in the absoluteUrl call is completely optional but allows you to modify the hostname if you want to be calling APIs from a different localhost address.</p><p>This enables you to test your code locally and deploy it to a live URL without needing to change any hardcoded hostnames in between steps.</p><p>The module is just this small function which you are welcome to copy/paste if you’d prefer.</p><pre>function absoluteUrl (req, setLocalhost) {<br>  var protocol = &#39;https:&#39;<br>  var host = req ? req.headers.host : window.location.hostname<br>  if (host.indexOf(&#39;localhost&#39;) &gt; -1) {<br>    if (setLocalhost) host = setLocalhost<br>    protocol = &#39;http:&#39;<br>  }</pre><pre>  return {<br>    protocol: protocol,<br>    host: host<br>  }<br>}</pre><pre>module.exports = absoluteUrl</pre><h3>Conclusion</h3><p>Now you should have a Next.js app running on localhost:3000, Node.js Lambda functions running on localhost:8004, and an entire application that works the same locally as it does on live deployments. Lambda functions called in .getInitialProps works on the server, in the browser, locally, and live.</p><p>I hope this helps anyone exploring Now v2 for their current application, but be prepared for the official now dev to drop at any moment 🎉</p><p><strong>P.S.</strong></p><p>Need someone to build your Next.js app? Contact <a href="https://www.digitalsurgeons.com/contact/">Digital Surgeons</a> and we’ll be happy to talk about partnering with you 😸</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5dfe7e1f663d" width="1" height="1" alt=""><hr><p><a href="https://medium.com/digital-surgeons-engineering/how-to-set-up-a-local-development-environment-for-serverless-next-js-5dfe7e1f663d">How to set up a local development environment for serverless Next.js</a> was originally published in <a href="https://medium.com/digital-surgeons-engineering">Digital Surgeons Engineering</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[WKT, GEOJSON, and Google Maps]]></title>
            <link>https://medium.com/digital-surgeons-engineering/wkt-geojson-and-google-maps-67a66097f69b?source=rss-ad55bb067148------2</link>
            <guid isPermaLink="false">https://medium.com/p/67a66097f69b</guid>
            <category><![CDATA[google-maps]]></category>
            <category><![CDATA[npm]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[mapbox]]></category>
            <dc:creator><![CDATA[Jake Burden]]></dc:creator>
            <pubDate>Sat, 10 Nov 2018 02:13:26 GMT</pubDate>
            <atom:updated>2020-09-11T14:46:34.656Z</atom:updated>
            <content:encoded><![CDATA[<p>I was challenged with visualizing voting districts in the state of Connecticut using Google maps required finding a public dataset of coordinates, and rendering those coordinates as a data layer on Google Maps. The goal of this short article is to outline what worked for me. I hope that it can be found as a small reference for someone else who might be in midst of a similar project.</p><h4>How to render a well-known text multipolygon string as a Google Maps data layer.</h4><p>To be concrete, I needed to render House and Senate districts in Connecticut. Some public datasets I found, such as <a href="https://data.ct.gov/api/views/w72a-m9it/rows.json?accessType=DOWNLOAD">this one on data.ct.gov</a>, contained what seemed to obviously be coordinate information. I had a feeling that I would need the data to be <a href="http://geojson.org/">GEOJSON</a>, a JSON format that map software can typically use to show boundaries. However, what I found was not GEOJSON. It was a JSON file, but with coordinate data in a format that I have never seen before:</p><pre>“MULTIPOLYGON (((-72.666264 41.7891380000001, -72.66…</pre><p>I initially referred to this as a “MULTIPOLYGON string”. What I didn’t realize at the time was that there was already a name for this format of coordinate data called “WKT”, or “<a href="http://en.wikipedia.org/wiki/Well-known_text">well-known text</a>.&quot;</p><p>An example MULTIYPOLYGON well-known text string on Wikipedia looks like this:</p><pre><br>MULTIPOLYGON (((40 40, 20 45, 45 30, 40 40)),<br>((20 35, 10 30, 10 10, 30 5, 45 20, 20 35),<br>(30 20, 20 15, 20 25, 30 20)))</pre><p>Notice that the first and last pair of numbers in a set of parenthesis are the inverse of each other.</p><p>So at this point I realized that I needed to convert this set of coordinates from WKT, to GEOJSON. In other words, I needed a WKT _parser_.</p><p>After some searching, I found that Esri had open sourced a WKT/GEOJSON parser called <a href="https://github.com/Esri/terraformer-wkt-parser">terraformer-wkt-parser</a>.</p><p>From here, I was able to get a GEOJSON output of the multipolygon string by calling the .parse method.</p><pre><br>var WKT = require(‘terraformer-wkt-parser’)</pre><pre>var multipolygon = getMultipolygon(data) // simplified function<br>var geojson = WKT.parse(multipolygon)<br></pre><h4>Getting GEOJSON into Google Maps</h4><p>This part was a little tricky at first. The docs for Google Maps make it obvious of how to load GEOJSON from an external source with a convenience method, but it’s a little less easy to see how to pass in a local string of GEOJSON.</p><p>Prying through the docs a little further, I found the documentation mentions an <a href="https://developers.google.com/maps/documentation/javascript/reference/data#Data.addGeoJson">addGeoJSON</a> method. This gave me the confidence to finally start loading Google Maps on the page.</p><p>After dealing with getting an API key and setting up billing (yes, you now need a credit card on file to do anything dynamic with Google Maps), I started adding Google Maps to my code.</p><pre><br>var WKT = require(‘terraformer-wkt-parser’)<br>var maps = require(‘google-maps’)</pre><pre>var multipolygon = getMultipolygon(data) // simplified function<br>var geojson = WKT.parse(multipolygon)</pre><pre>maps.load(function (google) {<br> var map = new google.maps.Map(document.getElementById(‘map’), {<br> zoom: 11,<br>  mapTypeId: ‘terrain’<br> })</pre><pre> map.data.addGeoJson(geojson)<br>})<br></pre><p>HOWEVER! This does not work exactly. It’s missing two things. One is that Google Maps has a specific scheme for GEOJSON. The other is that we’re not telling Google Maps where to center the map.</p><p>The proper scheme for Google Maps GEOJSON was easy enough to create, I just needed to wrap the parsed GEOJSON in some meta information.</p><pre><br>var feature = {<br> type: ‘Feature’,<br> geometry: geojson, // pass parsed GEOJSON here<br> properties: {<br> name: (isHouse ? ‘House’ : ‘Senate’) + ‘ District ‘ + districtNum<br> }<br>}<br></pre><p>The second issue, finding out how to tell what the center coordinates of a huge multiploygon string would be, required a little more searching. I found on an old forum, which I can’t remember the name of anymore, that was I was looking for was known as the visual center or the “pole of inaccessibility”, and not necessarily the geometric center.</p><p>I did what any JavaScript developer would do at this point. Google “pole of inaccessibility npm github”. That’s where I found my holy grail. A module published my Mapbox called <a href="https://github.com/mapbox/polylabel">polylabel</a>. They described it as “A fast algorithm for finding the pole of inaccessibility of a polygon (in JavaScript and C++)” and using it was super easy.</p><pre><br>var polylable = require(‘<a href="http://twitter.com/mapbox/polylabel">@mapbox/polylabel</a>’)<br>var center = polylable(geojson.coordinates[0])<br></pre><p>All together my code ended up looking like this:</p><pre><br>var WKT = require(‘terraformer-wkt-parser’)<br>var maps = require(‘google-maps’)<br>var polylable = require(‘<a href="http://twitter.com/mapbox/polylabel">@mapbox/polylabel</a>’)</pre><pre>var multipolygon = getMultipolygon(data) // simplified function<br>var geojson = WKT.parse(multipolygon)<br>var center = polylable(geojson.coordinates[0])</pre><pre>maps.load(function (google) {<br> var map = new google.maps.Map(document.getElementById(‘map’), {<br> zoom: 11,<br> mapTypeId: ‘terrain’,<br> center: {lat: center[1], lng: center[0]}<br>})<br> <br> var feature = {<br>   type: ‘Feature’,<br>   geometry: geojson, // pass parsed GEOJSON here<br>   properties: {<br>   name: (isHouse ? ‘House’ : ‘Senate’) + ‘ District ‘ + districtNum<br>   }<br> }</pre><pre>  map.data.addGeoJson(feature)<br>})</pre><p>With that, we had rendered data layers from multipolygon strings!</p><p>Here is what the output looked like:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/605/1*upmGybEX3Z0kCawNj0Tp3Q.png" /></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=67a66097f69b" width="1" height="1" alt=""><hr><p><a href="https://medium.com/digital-surgeons-engineering/wkt-geojson-and-google-maps-67a66097f69b">WKT, GEOJSON, and Google Maps</a> was originally published in <a href="https://medium.com/digital-surgeons-engineering">Digital Surgeons Engineering</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Process streaming JSON with Node.js]]></title>
            <link>https://medium.com/@Jekrb/process-streaming-json-with-node-js-d6530cde72e9?source=rss-ad55bb067148------2</link>
            <guid isPermaLink="false">https://medium.com/p/d6530cde72e9</guid>
            <category><![CDATA[nodejs]]></category>
            <category><![CDATA[json]]></category>
            <category><![CDATA[pump]]></category>
            <category><![CDATA[stream]]></category>
            <category><![CDATA[api]]></category>
            <dc:creator><![CDATA[Jake Burden]]></dc:creator>
            <pubDate>Mon, 09 Apr 2018 22:29:04 GMT</pubDate>
            <atom:updated>2019-01-10T03:50:28.042Z</atom:updated>
            <content:encoded><![CDATA[<blockquote>I’m going to show you how to process an infinite amount of streaming JSON.</blockquote><p>I’ve been automating tasks with various services that offer JSON APIs in my free time lately. The programs I’ve written for handling data from those services turned out to be “shaped” the same way. In an abstract sense:</p><ul><li>GET data from a JSON API</li><li>Parse chunks of JSON as it arrives</li><li>Do something with each row of parsed JSON</li><li>Write the processed data somewhere</li></ul><p>In code it tends to look something like this:</p><h3>jake ⿳⿻ on Twitter</h3><p>pump( hyperquest(source), JSONStream.parse(&#39;goodstuff.*&#39;), through(write, end), sink )</p><p>We’ll start by making a basic http server that responds to every request with an infinite stream of data. As long as the client request stays open, this server will continue responding with <a href="https://en.wikipedia.org/wiki/JSON_streaming#Line-delimited_JSON"><em>ndjson</em></a>.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/377c82269d2da34e5e98e56c115768af/href">https://medium.com/media/377c82269d2da34e5e98e56c115768af/href</a></iframe><p>The response header is set to <em>“application/json” </em>so that I can see the streaming ndjson in Firefox by visiting <a href="http://localhost:9090,">http://localhost:9090</a>. The next number in the sequence is written to the browser every 100ms. Here is what that looks like:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/396/1*XmzaAaApt1KKnnbFB2Wk6Q.gif" /></figure><p>How might we process this infinite stream of data? It’s not a regular JSON file that we can loop through or map over. We have to think about processing this <a href="https://github.com/pull-stream/pull-stream#design-goals--rationale">data over time rather than in space</a> as it’s so eloquently articulated in the pull-stream docs.</p><h3>Streaming HTTP</h3><p>I tend to use <a href="https://github.com/substack/hyperquest"><em>hyperquest</em></a>, but you can use <a href="https://github.com/request/request"><em>request</em></a> or something else that implements a Stream interface.</p><pre>hyperquest(source)</pre><h3>Streaming JSON parser</h3><p>To parse JSON over a stream from most API services you should use <a href="https://github.com/dominictarr/JSONStream"><em>JSONStream</em></a>. It works great for valid JSON sets. In this example I’ll be using <a href="https://github.com/maxogden/ndjson"><em>ndjson</em></a><em> </em>instead, because my server is responding with an infinite stream of newline-delimited JSON.</p><pre>hyperquest(source)<br>  .pipe(ndjson.parse())</pre><h3>Processing JSON in a duplex stream</h3><p>Each row of JSON will be parsed after this point in the pipeline. We can now process each row as a regular object. Since the value in each object is a number, lets do a <strong>basic example of squaring the number:</strong></p><p>We’ll use <a href="https://github.com/rvagg/through2"><em>through2</em></a><em> </em>to create a duplex stream that will transform the data flowing through this pipeline. Sometimes I’ll use <a href="https://github.com/substack/to2/"><em>to2</em></a><em> </em>if a transformation is the last step of the pipeline, but for this example, we’ll use <em>through2</em>.</p><p>We can use the through.obj method to pipe the ndjson parsed object directly to the through stream. To keep the pipeline short, we’ll create a named write function to process the row and pass that to the through stream.</p><p>There are two ways to pass data in <em>through2</em>. You can call this.push(data) and then explicitly call next() when you’re ready for the through stream to get its next chunk of data. Or you can call next(null, data) as we do below. This will also pass your data through the stream and call for the next chunk.</p><p>Unless the next stream in the pipeline is also going to be in <a href="https://nodejs.org/api/stream.html#stream_object_mode">objectMode</a>, we’ll have to make sure that Number we are passing in next is cast as a String. To make the output easy to parse, we’ll add a newline to the end.</p><pre>hyperquest(source)<br>  .pipe(ndjson.parse())<br>  .pipe(through.obj(write))</pre><pre>function write (row, enc, next) {<br>  next(null, String(row.value * row.value) + &#39;\n&#39;)<br>}</pre><h3>Write the data</h3><p>The pipeline is 3/4 of the way finished. We are reading ndjson from a source, parsing it as JSON objects, and processing each row of JSON. Now we have to write this transformed data somewhere. We’ll write it to stdout for this example by adding .pipe(process.stdout) to the pipleine.</p><pre>hyperquest(source)<br>  .pipe(ndjson.parse())<br>  .pipe(through.obj(write))<br>  .pipe(process.stdout)</pre><pre>function write (row, enc, next) {<br>  next(null, String(row.value * row.value) + &#39;\n&#39;)<br>}</pre><h3>Safe streams with pump()</h3><p>We’ve got a full pipeline now! It’s also a good habit to use a module called <a href="https://github.com/mafintosh/pump"><em>pump</em></a><em> </em>to handle the streams. Pump handles closing streams if the destination closes early or errors, and it allows you to pass a callback at the end of your pipeline to know when it’s finished or if any of your streams erred without having to explicitly listen for an error event on each one. Here is the above code using pump rather than .pipe :</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/b0cfb6bfc1103620edc3f1e4bfc127e4/href">https://medium.com/media/b0cfb6bfc1103620edc3f1e4bfc127e4/href</a></iframe><p>If we run our server in one terminal tab, and run the client in another, we should now have an infinite stream of data being processed!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*d28areKnkUvBBJ3e5c-DPg.gif" /><figcaption>server and client running to process an infinite stream of data</figcaption></figure><p><em>to see more examples, check the modules linked at the bottom of this </em><a href="https://github.com/jekrb/shopify-cp#see-also"><em>readme</em></a></p><p><em>Edit: Since writing this, a new Streams API has been released. You can now call require(‘stream’).pipeline for the same functionality as the </em><em>pump npm module.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d6530cde72e9" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>