<?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 Hugo Di Francesco on Medium]]></title>
        <description><![CDATA[Stories by Hugo Di Francesco on Medium]]></description>
        <link>https://medium.com/@hugo__df?source=rss-8d547401ba90------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*Rb-aDjpTtV1UZA4O.jpeg</url>
            <title>Stories by Hugo Di Francesco on Medium</title>
            <link>https://medium.com/@hugo__df?source=rss-8d547401ba90------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Tue, 17 Nov 2026 10:37:06 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@hugo__df/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[How to integrate a Python/Ruby/PHP shell script with Node.js using child_process.spawn]]></title>
            <link>https://medium.com/free-code-camp/how-to-integrate-a-python-ruby-php-shell-script-with-node-js-using-child-process-spawn-e26ca3268a11?source=rss-8d547401ba90------2</link>
            <guid isPermaLink="false">https://medium.com/p/e26ca3268a11</guid>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[tech]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[nodejs]]></category>
            <dc:creator><![CDATA[Hugo Di Francesco]]></dc:creator>
            <pubDate>Mon, 04 Feb 2019 00:00:00 GMT</pubDate>
            <atom:updated>2019-02-12T23:04:01.902Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*mtP3Ak9ndB1jJo0mauPu5w.jpeg" /><figcaption><a href="https://unsplash.com/@ecasap?utm_medium=referral&amp;utm_campaign=photographer-credit&amp;utm_content=creditBadge">Elaine Casap</a> on Unsplash</figcaption></figure><p>There are occasions when running a Python/Ruby/PHP shell script from Node.js is necessary. This post looks at best practices around leveraging child_process.spawn to encapsulate this call in Node.js/JavaScript.</p><p>The goal here is to have an interoperability layer between Node.js and an outside shell. This is a quick workaround if some other part of your system isn’t developed in JavaScript.</p><p>We’ll use spawn over exec because we’re talking about passing data and potentially large amounts of it. To understand the difference between child_process.spawn and child_process.exec see “<a href="https://www.hacksparrow.com/difference-between-spawn-and-exec-of-node-js-child_process.html">Difference between spawn and exec of Node.js child_process</a>”.</p><p>The long and short of it is use exec for small amounts of data (under 200k) using a Buffer interface and spawn for larger amounts using a stream interface.</p><p>spawn has a more verbose syntax for some of the use-cases we’ll look at. It’s more serviceable for integrating with Ruby/Python/PHP since we might get more data than a couple of lines of text.</p><p>Full examples <a href="https://github.com/HugoDF/node-run-python">github.com/HugoDF/node-run-python</a>.</p><p>The following examples contain 2 sections:</p><ul><li>The part that actually runs the shell command, usually a function called run, and</li><li>an IIFE (“immediately invoked function expression”) that actually calls it, (async () =&gt; { await run() })(). This IIFE is a nice pattern enabled by async/await (see <a href="https://codewithhugo.com/async-js/#async-await">Async JS: history, patterns and gotchas</a>) but it’s just there for illustration purposes since it represents the call to the wrapped spawn call from another part of your application.</li></ul><h3>Call a shell command and log it</h3><p>Using spawn is overkill in this situation since echo is only going to return what’s passed to it.</p><p>The example is pretty self-explanatory and shows how to use child_process.spawn to “shell out” and read that data back.</p><p>spawn takes the executable to call as the first parameter and optionally an array of options/parameters for the executable as the second parameter.</p><pre>const { spawn } = require(&#39;child_process&#39;);</pre><pre>function run() {<br>  const process = spawn(&#39;echo&#39;, [&#39;foo&#39;]);<br>  process.stdout.on(<br>    &#39;data&#39;,<br>    (data) =&gt; console.log(data.toString())<br>  );<br>}</pre><pre>(() =&gt; {<br>  try {<br>    run()<br>    <em>// process.exit(0)<br>  </em>} catch (e) {<br>    console.error(e.stack);<br>    process.exit(1);<br>  }<br>})();</pre><h3>Call Python for its version</h3><p>We’ll move quite quickly to showcase how we would do something similar to the above with Python. Note again how --version is passed inside of an array.</p><p>We also create a nice logger to differentiate between stdout and stderr and bind to them. Since spawn returns an instance which has stdout and stderr event emitters, we can bind our logOutput function to &#39;data&#39; event using .on(&#39;data&#39;, () =&gt; { /* our callback function */ }).</p><p>Another interesting tidbit is that python --version outputs the version to stderr. The inconsistencies around whether *NIX executables use exit codes, stderr and stdout on success/error are a quirk that we’ll have to bear in mind while integrating Python/Ruby/other with Node.js.</p><pre>const { spawn } = require(&#39;child_process&#39;)</pre><pre>const logOutput = (name) =&gt; (data) =&gt; console.log(`[${name}] ${data.toString()}`)</pre><pre>function run() {<br>  const process = spawn(&#39;python&#39;, [&#39;--version&#39;]);</pre><pre>process.stdout.on(<br>    &#39;data&#39;,<br>    logOutput(&#39;stdout&#39;)<br>  );</pre><pre>process.stderr.on(<br>    &#39;data&#39;,<br>    logOutput(&#39;stderr&#39;)<br>  );<br>}</pre><pre>(() =&gt; {<br>  try {<br>    run()<br>    process.exit(0)<br>  } catch (e) {<br>    console.error(e.stack);<br>    process.exit(1);<br>  }<br>})();</pre><p>Output:</p><pre>$ node run.js</pre><pre>[stderr] Python 2.7.13</pre><h3>Call a Python script from Node</h3><p>We’ll now run a fully-fledged Python script (although it could just as well be Ruby, PHP, shell etc.) from Node.js.</p><p>This is script.py, it just logs out argv (the “argument vector”, ie. [&#39;path/to/executable&#39;, /* command line arguments ])</p><pre>import sys<br>print(sys.argv)</pre><p>Like in the previous example, we’ll just call spawn with python with the path to the Python script (./script.py) in the second parameter.</p><p>Here comes another gotcha of integrating scripts in this fashion. In this example, the path to the script is based on the working directory from which node is called.</p><p>There is a workaround, of course, using the path module and __dirname, which for example could resolve a other-script.py co-located with the JavaScript file/Node module calling spawn using: require(&#39;path&#39;).resolve(__dirname, &#39;./other-script.py&#39;).</p><pre>const { spawn } = require(&#39;child_process&#39;)</pre><pre>const logOutput = (name) =&gt; (data) =&gt; console.log(`[${name}] ${data.toString()}`)</pre><pre>function run() {<br>  const process = spawn(&#39;python&#39;, [&#39;./script.py&#39;]);</pre><pre>process.stdout.on(<br>    &#39;data&#39;,<br>    logOutput(&#39;stdout&#39;)<br>  );</pre><pre>process.stderr.on(<br>    &#39;data&#39;,<br>    logOutput(&#39;stderr&#39;)<br>  );<br>}</pre><pre>(() =&gt; {<br>  try {<br>    run()<br>    // process.exit(0)<br>  } catch (e) {<br>    console.error(e.stack);<br>    process.exit(1);<br>  }<br>})();</pre><p>Output:</p><pre>$ node run.js</pre><pre>\[stdout\] [&#39;./script.py&#39;]</pre><h3>Pass arguments to a Python script from Node.js using child_process.spawn</h3><p>The next step of integration is to be able to pass data from the Node/JavaScript code to the Python script.</p><p>In order to do this, we’ll just pass more shell arguments using the arguments array (the second parameter to spawn).</p><pre>const { spawn } = require(&#39;child_process&#39;)</pre><pre>const logOutput = (name) =&gt; (data) =&gt; console.log(`[${name}] ${data.toString()}`)</pre><pre>function run() {<br>  const process = spawn(&#39;python&#39;, [&#39;./script.py&#39;, &#39;my&#39;, &#39;args&#39;]);</pre><pre>  process.stdout.on(<br>    &#39;data&#39;,<br>    logOutput(&#39;stdout&#39;)<br>  );</pre><pre>  process.stderr.on(<br>    &#39;data&#39;,<br>    logOutput(&#39;stderr&#39;)<br>  );<br>}</pre><pre>(() =&gt; {<br>  try {<br>    run()<br>    // process.exit(0)<br>  } catch (e) {<br>    console.error(e.stack);<br>    process.exit(1);<br>  }<br>})();</pre><p>Our script.py will also just log out the argv except for the first element (which is the path to the script).</p><pre>import sys<br>print(sys.argv)[1:]</pre><p>Here’s the output:</p><pre>$ node run.js<br>\[stdout\] [&#39;my&#39;, &#39;args&#39;]</pre><h3>Read child_process.spawn output from Node.js</h3><p>It’s nice to be able to pass data down to the Python script. We’re still not able to get the data from the Python script back in a format that we’re able to leverage in our Node.js/JavaScript application.</p><p>The solution to this is to wrap the whole spawn -calling function into a Promise. This allows us to decide when we want to resolve or reject.</p><p>To keep track of the Python script’s output stream(s), we manually buffer the output using arrays (one for stdout and another for stderr).</p><p>We also add a listener for &#39;exit&#39; using spawn().on(&#39;exit&#39;, (code, signal) =&gt; { /* probably call resolve() */ }). This is where we will tend to resolve/reject the Promise’s value(s) from the Python/Ruby/other script.</p><pre>const { spawn } = require(&#39;child_process&#39;)</pre><pre>const logOutput = (name) =&gt; (data) =&gt; console.log(`[${name}] ${data}`)</pre><pre>function run() {<br>  return new Promise((resolve, reject) =&gt; {<br>    const process = spawn(&#39;python&#39;, [&#39;./script.py&#39;, &#39;my&#39;, &#39;args&#39;]);</pre><pre>    const out = []<br>    process.stdout.on(<br>      &#39;data&#39;,<br>      (data) =&gt; {<br>        out.push(data.toString());<br>        logOutput(&#39;stdout&#39;)(data);<br>      }<br>    );</pre><pre>    const err = []<br>    process.stderr.on(<br>      &#39;data&#39;,<br>      (data) =&gt; {<br>        err.push(data.toString());<br>        logOutput(&#39;stderr&#39;)(data);<br>      }<br>    );</pre><pre>    process.on(&#39;exit&#39;, (code, signal) =&gt; {<br>      logOutput(&#39;exit&#39;)(`${code} (${signal})`)<br>      resolve(out);<br>    });<br>  });<br>}</pre><pre>(async () =&gt; {<br>  try {<br>    const output = await run()<br>    logOutput(&#39;main&#39;)(output)<br>    process.exit(0)<br>  } catch (e) {<br>    console.error(e.stack);<br>    process.exit(1);<br>  }<br>})();</pre><p>Output:</p><pre>$ node run.js</pre><pre>\[stdout\] [&#39;my&#39;, &#39;args&#39;]<br>\[main\] [&#39;my&#39;, &#39;args&#39;]</pre><h3>Handle errors from child_process.spawn</h3><p>Next up we need to handle errors from the Python/Ruby/shell script at the Node.js/JavaScript level.</p><p>The main way that a *NIX executable signals that it errored are by using a 1 exit code. That’s why the .on(&#39;exit&#39; handler now does a check against code === 0 before deciding whether to resolve or reject with value(s).</p><pre>const { spawn } = require(&#39;child_process&#39;)</pre><pre>const logOutput = (name) =&gt; (data) =&gt; console.log(`[${name}] ${data}`)</pre><pre>function run() {<br>  return new Promise((resolve, reject) =&gt; {<br>    const process = spawn(&#39;python&#39;, [&#39;./script.py&#39;, &#39;my&#39;, &#39;args&#39;]);</pre><pre>const out = []<br>    process.stdout.on(<br>      &#39;data&#39;,<br>      (data) =&gt; {<br>        out.push(data.toString());<br>        logOutput(&#39;stdout&#39;)(data);<br>      }<br>    );</pre><pre>const err = []<br>    process.stderr.on(<br>      &#39;data&#39;,<br>      (data) =&gt; {<br>        err.push(data.toString());<br>        logOutput(&#39;stderr&#39;)(data);<br>      }<br>    );</pre><pre>process.on(&#39;exit&#39;, (code, signal) =&gt; {<br>      logOutput(&#39;exit&#39;)(`${code} (${signal})`)<br>      if (code === 0) {<br>        resolve(out);<br>      } else {<br>        reject(new Error(err.join(&#39;\n&#39;)))<br>      }<br>    });<br>  });<br>}</pre><pre>(async () =&gt; {<br>  try {<br>    const output = await run()<br>    logOutput(&#39;main&#39;)(output)<br>    process.exit(0)<br>  } catch (e) {<br>    console.error(&#39;Error during script execution &#39;, e.stack);<br>    process.exit(1);<br>  }<br>})();</pre><p>Output:</p><pre>$ node run.js</pre><pre>[stderr] Traceback (most recent call last):<br>    File &quot;./script.py&quot;, line 3, in &lt;module&gt;<br>    print(sy.argv)[1:]<br>NameError: name &#39;sy&#39; is not defined</pre><pre>Error during script execution Error: Traceback (most recent call last):<br>    File &quot;./script.py&quot;, line 3, in &lt;module&gt;<br>    print(sy.argv)[1:]<br>NameError: name &#39;sy&#39; is not defined</pre><pre>at ChildProcess.process.on (/app/run.js:33:16)<br>    at ChildProcess.emit (events.js:182:13)<br>    at Process.ChildProcess._handle.onexit (internal/child_process.js:240:12)</pre><h3>Pass structured data from Python/Ruby to Node.js/JavaScript</h3><p>The final step to full integration between Ruby/Python/PHP/shell scripts and our Node.js/JavaScript application layer is to be able to pass structured data back from the script up to Node.js/JavaScript.</p><p>The simplest structured data format that tends to be available in both Python/Ruby/PHP and Node.js/JavaScript is JSON.</p><p>In the Python script, we print the json.dumps() output of a dictionary, see script.py:</p><pre>import sys<br>import json</pre><pre>send_message_back = {<br>  &#39;arguments&#39;: sys.argv[1:],<br>  &#39;message&#39;: &quot;&quot;&quot;Hello,<br>This is my message.</pre><pre>To the world&quot;&quot;&quot;<br>}</pre><pre>print(json.dumps(send_message_back))</pre><p>In Node, we add some JSON-parsing logic (using JSON.parse) in the &#39;exit&#39; handler.</p><p>A gotcha at this point is if, for example JSON.parse() fails due to badly-formed JSON, we need to propagate that error up. Hence the try/catch where the catch clause reject-s the potential error: try { resolve(JSON.parse(out[0])) } catch(e) { reject(e) }.</p><pre>const { spawn } = require(&#39;child_process&#39;)</pre><pre>const logOutput = (name) =&gt; (message) =&gt; console.log(`[${name}] ${message}`)</pre><pre>function run() {<br>  return new Promise((resolve, reject) =&gt; {<br>    const process = spawn(&#39;python&#39;, [&#39;./script.py&#39;, &#39;my&#39;, &#39;args&#39;]);</pre><pre>    const out = []<br>    process.stdout.on(<br>      &#39;data&#39;,<br>      (data) =&gt; {<br>        out.push(data.toString());<br>        logOutput(&#39;stdout&#39;)(data);<br>      }<br>    );</pre><pre>    const err = []<br>    process.stderr.on(<br>      &#39;data&#39;,<br>      (data) =&gt; {<br>        err.push(data.toString());<br>        logOutput(&#39;stderr&#39;)(data);<br>      }<br>    );</pre><pre>   process.on(&#39;exit&#39;, (code, signal) =&gt; {<br>      logOutput(&#39;exit&#39;)(`${code} (${signal})`)<br>      if (code !== 0) {<br>        reject(new Error(err.join(&#39;\n&#39;)))<br>        return<br>      }<br>      try {<br>        resolve(JSON.parse(out[0]));<br>      } catch(e) {<br>        reject(e);<br>      }<br>    });<br>  });<br>}</pre><pre>(async () =&gt; {<br>  try {<br>    const output = await run()<br>    logOutput(&#39;main&#39;)(output.message)<br>    process.exit(0)<br>  } catch (e) {<br>    console.error(&#39;Error during script execution &#39;, e.stack);<br>    process.exit(1);<br>  }<br>})();</pre><p>Output:</p><pre>$ node run.js</pre><pre>[stdout] {&quot;message&quot;: &quot;Hello,\nThis is my message.\n\nTo the world&quot;, &quot;arguments&quot;: [&quot;my&quot;, &quot;args&quot;]}</pre><pre>[main] Hello,<br>This is my message.</pre><pre>To the world</pre><p>That’s it! Thanks for reading :)</p><p>I’ve got mentoring spots open at <a href="https://mentorcruise.com/mentor/HugoDiFrancesco/">https://mentorcruise.com/mentor/HugoDiFrancesco/</a>. Do that if you want Node.js/JavaScript/career mentoring or feel free to tweet at me <a href="https://twitter.com/hugo__df">@hugo__df</a></p><p><em>Originally published at </em><a href="https://codewithhugo.com/integrate-python-ruby-php-shell-with-node-js/"><em>codewithhugo.com</em></a><em> on February 4, 2019.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e26ca3268a11" width="1" height="1" alt=""><hr><p><a href="https://medium.com/free-code-camp/how-to-integrate-a-python-ruby-php-shell-script-with-node-js-using-child-process-spawn-e26ca3268a11">How to integrate a Python/Ruby/PHP shell script with Node.js using child_process.spawn</a> was originally published in <a href="https://medium.com/free-code-camp">We’ve moved to freeCodeCamp.org/news</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Post Frequency: from prototype to production with Vue + Node]]></title>
            <description><![CDATA[<div class="medium-feed-item"><p class="medium-feed-image"><a href="https://medium.com/swlh/post-frequency-from-prototype-to-production-with-vue-node-349340287e7e?source=rss-8d547401ba90------2"><img src="https://cdn-images-1.medium.com/max/1000/1*i9vRPfLZy6MFW6wiygZVMA.jpeg" width="1000"></a></p><p class="medium-feed-snippet">If you want to ship, use the tools you know.&#x200A;&#x2014;&#x200A;A lot of people</p><p class="medium-feed-link"><a href="https://medium.com/swlh/post-frequency-from-prototype-to-production-with-vue-node-349340287e7e?source=rss-8d547401ba90------2">Continue reading on The Startup »</a></p></div>]]></description>
            <link>https://medium.com/swlh/post-frequency-from-prototype-to-production-with-vue-node-349340287e7e?source=rss-8d547401ba90------2</link>
            <guid isPermaLink="false">https://medium.com/p/349340287e7e</guid>
            <category><![CDATA[vuejs]]></category>
            <category><![CDATA[productivity]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[nodejs]]></category>
            <dc:creator><![CDATA[Hugo Di Francesco]]></dc:creator>
            <pubDate>Mon, 26 Nov 2018 00:00:00 GMT</pubDate>
            <atom:updated>2018-11-27T07:21:33.160Z</atom:updated>
        </item>
        <item>
            <title><![CDATA[A simple JavaScript/Node coding setup on Mac OS X]]></title>
            <description><![CDATA[<div class="medium-feed-item"><p class="medium-feed-image"><a href="https://medium.com/free-code-camp/a-simple-javascript-node-coding-setup-on-mac-os-x-1face26dd522?source=rss-8d547401ba90------2"><img src="https://cdn-images-1.medium.com/max/1500/1*cScHqTcGnR_2cacUtzxYSQ.jpeg" width="1500"></a></p><p class="medium-feed-snippet">Here&#x2019;s how I get productive for JavaScript/Node on Mac OS.</p><p class="medium-feed-link"><a href="https://medium.com/free-code-camp/a-simple-javascript-node-coding-setup-on-mac-os-x-1face26dd522?source=rss-8d547401ba90------2">Continue reading on We’ve moved to freeCodeCamp.org/news »</a></p></div>]]></description>
            <link>https://medium.com/free-code-camp/a-simple-javascript-node-coding-setup-on-mac-os-x-1face26dd522?source=rss-8d547401ba90------2</link>
            <guid isPermaLink="false">https://medium.com/p/1face26dd522</guid>
            <category><![CDATA[productivity]]></category>
            <category><![CDATA[mac]]></category>
            <category><![CDATA[nodejs]]></category>
            <category><![CDATA[javascript]]></category>
            <dc:creator><![CDATA[Hugo Di Francesco]]></dc:creator>
            <pubDate>Mon, 19 Nov 2018 00:00:00 GMT</pubDate>
            <atom:updated>2018-11-20T20:02:47.040Z</atom:updated>
        </item>
        <item>
            <title><![CDATA[Progress and roadblocks: a journey into open-source]]></title>
            <description><![CDATA[<div class="medium-feed-item"><p class="medium-feed-image"><a href="https://medium.com/free-code-camp/progress-and-roadblocks-a-journey-into-open-source-f88dfaaa45e6?source=rss-8d547401ba90------2"><img src="https://cdn-images-1.medium.com/max/1500/1*7JFvBJzuRNi2rW--xJLjTw.jpeg" width="1500"></a></p><p class="medium-feed-snippet">Enhancing generators for ES6 in the Sequelize CLI</p><p class="medium-feed-link"><a href="https://medium.com/free-code-camp/progress-and-roadblocks-a-journey-into-open-source-f88dfaaa45e6?source=rss-8d547401ba90------2">Continue reading on We’ve moved to freeCodeCamp.org/news »</a></p></div>]]></description>
            <link>https://medium.com/free-code-camp/progress-and-roadblocks-a-journey-into-open-source-f88dfaaa45e6?source=rss-8d547401ba90------2</link>
            <guid isPermaLink="false">https://medium.com/p/f88dfaaa45e6</guid>
            <category><![CDATA[github]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[open-source]]></category>
            <dc:creator><![CDATA[Hugo Di Francesco]]></dc:creator>
            <pubDate>Wed, 07 Nov 2018 00:00:00 GMT</pubDate>
            <atom:updated>2018-11-07T10:39:39.684Z</atom:updated>
        </item>
        <item>
            <title><![CDATA[6 months of Code with Hugo, in numbers]]></title>
            <description><![CDATA[<div class="medium-feed-item"><p class="medium-feed-image"><a href="https://medium.com/swlh/6-months-of-code-with-hugo-in-numbers-98645e0a814e?source=rss-8d547401ba90------2"><img src="https://cdn-images-1.medium.com/max/1500/1*xELixl5I6nxYhUooRJ90zA.jpeg" width="1500"></a></p><p class="medium-feed-snippet">Going from 0 to small. A developer&#x2019;s journey starting a technical blog from scratch.</p><p class="medium-feed-link"><a href="https://medium.com/swlh/6-months-of-code-with-hugo-in-numbers-98645e0a814e?source=rss-8d547401ba90------2">Continue reading on The Startup »</a></p></div>]]></description>
            <link>https://medium.com/swlh/6-months-of-code-with-hugo-in-numbers-98645e0a814e?source=rss-8d547401ba90------2</link>
            <guid isPermaLink="false">https://medium.com/p/98645e0a814e</guid>
            <category><![CDATA[productivity]]></category>
            <category><![CDATA[content]]></category>
            <category><![CDATA[writing]]></category>
            <category><![CDATA[blogging]]></category>
            <dc:creator><![CDATA[Hugo Di Francesco]]></dc:creator>
            <pubDate>Sun, 21 Oct 2018 00:00:00 GMT</pubDate>
            <atom:updated>2018-10-22T06:06:32.316Z</atom:updated>
        </item>
        <item>
            <title><![CDATA[ObservableHQ notebooks for JavaScript demos and prototypes]]></title>
            <description><![CDATA[<div class="medium-feed-item"><p class="medium-feed-image"><a href="https://medium.com/@hugo__df/observablehq-notebooks-for-javascript-demos-and-prototypes-2da09370a13d?source=rss-8d547401ba90------2"><img src="https://cdn-images-1.medium.com/max/1500/1*XMJD_-C-G7B3eTOs03S_YQ.jpeg" width="1500"></a></p><p class="medium-feed-snippet">ObservableHQ is a platform being built by Mike Bostock (creator of the D3 visualisation library), Jeremy Ashkenas (&#x201C;Made CoffeeScript&#x2026;</p><p class="medium-feed-link"><a href="https://medium.com/@hugo__df/observablehq-notebooks-for-javascript-demos-and-prototypes-2da09370a13d?source=rss-8d547401ba90------2">Continue reading on Medium »</a></p></div>]]></description>
            <link>https://medium.com/@hugo__df/observablehq-notebooks-for-javascript-demos-and-prototypes-2da09370a13d?source=rss-8d547401ba90------2</link>
            <guid isPermaLink="false">https://medium.com/p/2da09370a13d</guid>
            <category><![CDATA[prototyping]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[productivity]]></category>
            <dc:creator><![CDATA[Hugo Di Francesco]]></dc:creator>
            <pubDate>Mon, 08 Oct 2018 00:00:00 GMT</pubDate>
            <atom:updated>2018-10-10T20:05:05.191Z</atom:updated>
        </item>
        <item>
            <title><![CDATA[How to impress interviewers by using recursion in JavaScript with ES6 features]]></title>
            <link>https://medium.com/free-code-camp/how-to-impress-interviewers-by-using-recursion-in-javascript-with-es6-features-a14c763110d7?source=rss-8d547401ba90------2</link>
            <guid isPermaLink="false">https://medium.com/p/a14c763110d7</guid>
            <category><![CDATA[tech]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[es6]]></category>
            <category><![CDATA[interview]]></category>
            <dc:creator><![CDATA[Hugo Di Francesco]]></dc:creator>
            <pubDate>Mon, 01 Oct 2018 00:00:00 GMT</pubDate>
            <atom:updated>2018-10-08T20:55:45.579Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*krm8DV5lopMRYxuH0DevlQ.jpeg" /><figcaption><a href="https://unsplash.com/@andremouton?utm_medium=referral&amp;utm_campaign=photographer-credit&amp;utm_content=creditBadge%20&quot;Download%20free%20do%20whatever%20you%20want%20high-resolution%20photos%20from%20Andre%20Mouton&quot;">Andre Mouton</a> on Unsplash</figcaption></figure><p>There’s nothing as flashy and useful for JavaScript interviews than recursion.</p><p>If you just want to be impressive with recursion in JavaScript, here are some semi real-world (technical test type) examples.</p><p>The short definition of a recursive solution to a problem (in computer science) is: don’t use iteration. This usually means a function has to call itself with a smaller instance of the same problem. It does this until it hits a trivial case (usually defined in the problem).</p><p>Hence, recursion is composed of a couple of steps.</p><p>In this post, we’ll discuss:</p><ul><li><a href="https://codewithhugo.com/impress-interviewers-with-recursion-in-javascript-with-es6-features#recursion-to-wrap-sequential-http-requests">🛰 Recursion to wrap sequential HTTP requests</a></li><li><a href="https://codewithhugo.com/impress-interviewers-with-recursion-in-javascript-with-es6-features#count-number-of-characters">📃 Count number of characters</a></li></ul><p>The examples for this post are also on <a href="http://beta.observablehq.com/">ObervableHQ</a>, which is a super cool tool that allows you to build JavaScript notebooks:</p><ul><li><a href="https://beta.observablehq.com/@hugodf/recursion-to-wrap-http-requests">Recursion to wrap sequential HTTP request</a></li><li><a href="https://beta.observablehq.com/@hugodf/count-something-in-something-else">Count number of characters</a></li></ul><h3>🛰 Recursion to wrap sequential HTTP requests</h3><p>Say you need to get multiple pages from a REST API and you’re forced to use the native HTTPS module, (<a href="https://beta.observablehq.com/@hugodf/recursion-to-wrap-http-requests">example here</a>). In this situation, we’ll be fetching comments from the Reddit API.</p><p>With this API:</p><ul><li>if there are more comments than fit in one response, it will return an after field in the data. This can be used as a query param in a request to get the next chunk of comments</li><li>if there are no more comments, after will be falsy</li></ul><p>That defines our terminating and recursive cases. We fetch data from the Reddit API and then either:</p><ul><li>after is falsy → <strong>terminating case</strong>, return the data</li><li>after is defined → <strong>recursive case</strong>, pass it to fetch the next page as well as data returned from the current call</li></ul><p>One of the tricks used here is passing an empty data array into the recursiveCommentFetch function from the first pass. This allows us to keep injecting more and more values as we go through each recursive call. We are able to resolve to the full set at the terminating case.</p><pre>const fetch = require(&#39;node-fetch&#39;);<br>const user = &#39;hugo__df&#39;;</pre><pre>function makeRedditCommentUrl(user, queryParams) {<br>  return `<a href="https://www.reddit.com/user/$%7Buser%7D/comments.json?${">https://www.reddit.com/user/${user}/comments.json?${</a><br>    Object.entries(queryParams)<br>      .filter(([k, v]) =&gt; Boolean(v))<br>      .map(<br>        ([k, v]) =&gt; `${k}=${v}`<br>      ).join(&#39;&amp;&#39;)<br>  }`;<br>}</pre><pre>function recursiveCommentFetch(user, data = [], { after, limit = 100 } = {}) {<br>  const url = makeRedditCommentUrl(user, { after, limit });<br>  return fetch(url)<br>    .then(res =&gt; res.json())<br>    .then(res =&gt; {<br>      const { after, children } = res.data;<br>      const newData = [...data, ...children];<br>      if (after) {<br>        // recursive case, there&#39;s a way to fetch more comments<br>        return recurseCommentFetch(user, newData, { after });<br>      }<br>      // base or terminating case<br>      return newData;<br>    });<br>}</pre><pre>recursiveCommentFetch(user)<br>  .then(comments =&gt; console.log(comments));</pre><p>I familiarized myself with this API by creating the following visualization for Reddit contributions (in GitHub’s contribution graph style). <a href="https://beta.observablehq.com/@hugodf/reddit-contributions-per-week-graph">See it here</a>. The <a href="https://accountableblogging.com/post-frequency">blog version is also live</a>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*H5rcQi_HW8UZTipm.png" /></figure><h3>📃 Count number of characters</h3><p>When the question goes something like this: “given an input, return an object containing how many times each character is present in the input” you’ll use this method.</p><p>There’s a <a href="https://beta.observablehq.com/@hugodf/count-something-in-something-else">live demo here</a>.</p><p>The terminating and recursive case isn’t immediately obvious, so there are a few leaps here:</p><ol><li>understanding that an input can be cast to a string, which can be .split into an Array (ie. most arbitrary input can be converted into an Array).</li><li>knowing how to recurse through an Array. It’s probably one of the easier/most common things to recurse through. But it takes seeing it a couple of times to start feeling comfortable doing it.</li></ol><p>That gives us the following situation for a recursive function:</p><ul><li>list/array of characters is empty → <strong>terminating case</strong>, return the characterToCount map</li><li>list/array of characters is not empty → <strong>recursive case</strong>, update characterToCountMap by incrementing/ initializing the current character’s entry. Call the recursive function with the updated map and the rest of the list/array.</li></ul><p>I’ve written a more complete post: <a href="https://codewithhugo.com/recursion-in-javascript-with-es6-destructuring-and-rest/spread/"><strong>Recursion in JavaScript with ES6, destructuring and rest/spread</strong></a>, which goes into more detail (examples and techniques) about how we can recurse through lists (arrays) in ES6 JavaScript. It explains things like the [firstCharacter, ...rest] notation.</p><pre>function recurseCountCharacters(<br>  [firstCharacter, ...rest],<br>  characterToCountMap = {}<br>) {<br>  const currentCharacterCount = characterToCountMap[firstCharacter] || 0;<br>  const newCharacterToCountMap = {<br>    ...characterToCountMap,<br>    [firstCharacter]: currentCharacterCount + 1<br>  };<br>  <br>  if (rest.length === 0) {<br>    // base/terminating case<br>    // -&gt; nothing characters left in the string<br>    return newCharacterToCountMap;<br>  }<br>  // recursive case<br>  return recurseCountCharacters(rest, newCharacterToCountMap);<br>}</pre><pre>function countCharacters(input) {<br>  return recurseCountCharacters(String(input).split(&#39;&#39;));  <br>}</pre><pre>console.log(countCharacters(1000000));<br>// { &quot;0&quot;:6, &quot;1&quot;: 1 }<br>console.log(countCharacters(&#39;some sentence&#39;));<br>// { &quot;s&quot;:2,&quot;o&quot;:1,&quot;m&quot;:1,&quot;e&quot;:4,&quot; &quot;:1,&quot;n&quot;:2,&quot;t&quot;:1,&quot;c&quot;:1}</pre><p>That’s how you breeze through interviews using recursion 🙂, running circles around those toy problems.</p><p>Recursive solutions to interview problems end up looking cooler and cleaner than iterative ones. They’re interviewer eye-candy.</p><p>For any questions, you can reach me on Twitter <a href="https://twitter.com/hugo__df">@hugo__df</a>.</p><p>Get all the posts of the week before anyone else in your inbox: <a href="https://buttondown.email/hugo">Code with Hugo newsletter</a>.</p><p><em>Originally published at </em><a href="https://codewithhugo.com/impress-interviewers-with-recursion-in-javascript-with-es6-features"><em>codewithhugo.com</em></a><em> on October 1, 2018.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a14c763110d7" width="1" height="1" alt=""><hr><p><a href="https://medium.com/free-code-camp/how-to-impress-interviewers-by-using-recursion-in-javascript-with-es6-features-a14c763110d7">How to impress interviewers by using recursion in JavaScript with ES6 features</a> was originally published in <a href="https://medium.com/free-code-camp">We’ve moved to freeCodeCamp.org/news</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Writing multiple Vue components in a single file]]></title>
            <description><![CDATA[<div class="medium-feed-item"><p class="medium-feed-image"><a href="https://medium.com/hackernoon/writing-multiple-vue-components-in-a-single-file-199871f6182e?source=rss-8d547401ba90------2"><img src="https://cdn-images-1.medium.com/max/1500/1*mXkIQoiULmbqr4V46DtuZA.jpeg" width="1500"></a></p><p class="medium-feed-snippet">Writing multiple components in one file is a pattern from React where some files contain multiple components.</p><p class="medium-feed-link"><a href="https://medium.com/hackernoon/writing-multiple-vue-components-in-a-single-file-199871f6182e?source=rss-8d547401ba90------2">Continue reading on HackerNoon.com »</a></p></div>]]></description>
            <link>https://medium.com/hackernoon/writing-multiple-vue-components-in-a-single-file-199871f6182e?source=rss-8d547401ba90------2</link>
            <guid isPermaLink="false">https://medium.com/p/199871f6182e</guid>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[multiple-vue-components]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[vue]]></category>
            <category><![CDATA[vue-component]]></category>
            <dc:creator><![CDATA[Hugo Di Francesco]]></dc:creator>
            <pubDate>Thu, 27 Sep 2018 00:00:00 GMT</pubDate>
            <atom:updated>2019-05-24T09:40:37.030Z</atom:updated>
        </item>
        <item>
            <title><![CDATA[A gentle introduction to GraphQL API integrations]]></title>
            <description><![CDATA[<div class="medium-feed-item"><p class="medium-feed-image"><a href="https://medium.com/free-code-camp/a-gentle-introduction-to-graphql-api-integrations-6564312d402c?source=rss-8d547401ba90------2"><img src="https://cdn-images-1.medium.com/max/2600/1*A6Cr5WakyAJjuES53YXBow.jpeg" width="3432"></a></p><p class="medium-feed-snippet">GraphQL is a great alternative to REST (or other HTTP API designs). This is a quick introduction to the core concepts around consuming a&#x2026;</p><p class="medium-feed-link"><a href="https://medium.com/free-code-camp/a-gentle-introduction-to-graphql-api-integrations-6564312d402c?source=rss-8d547401ba90------2">Continue reading on We’ve moved to freeCodeCamp.org/news »</a></p></div>]]></description>
            <link>https://medium.com/free-code-camp/a-gentle-introduction-to-graphql-api-integrations-6564312d402c?source=rss-8d547401ba90------2</link>
            <guid isPermaLink="false">https://medium.com/p/6564312d402c</guid>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[api]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[graphql]]></category>
            <dc:creator><![CDATA[Hugo Di Francesco]]></dc:creator>
            <pubDate>Mon, 10 Sep 2018 00:00:00 GMT</pubDate>
            <atom:updated>2018-09-25T14:32:30.786Z</atom:updated>
        </item>
        <item>
            <title><![CDATA[JavaScript GraphQL client requests in Node and the browser using `graphql.js`]]></title>
            <description><![CDATA[<div class="medium-feed-item"><p class="medium-feed-image"><a href="https://medium.com/hackernoon/javascript-graphql-client-requests-in-node-and-the-browser-using-graphql-js-1cdabfc4126b?source=rss-8d547401ba90------2"><img src="https://cdn-images-1.medium.com/max/1500/1*fF_5FsOTEX2oSRM-KcPhZw.jpeg" width="1500"></a></p><p class="medium-feed-snippet">An example consuming a GraphQL API in JavaScript from Node and the browser using graphql.js</p><p class="medium-feed-link"><a href="https://medium.com/hackernoon/javascript-graphql-client-requests-in-node-and-the-browser-using-graphql-js-1cdabfc4126b?source=rss-8d547401ba90------2">Continue reading on HackerNoon.com »</a></p></div>]]></description>
            <link>https://medium.com/hackernoon/javascript-graphql-client-requests-in-node-and-the-browser-using-graphql-js-1cdabfc4126b?source=rss-8d547401ba90------2</link>
            <guid isPermaLink="false">https://medium.com/p/1cdabfc4126b</guid>
            <category><![CDATA[graphqljs]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[javascript-graphql]]></category>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[graphql]]></category>
            <dc:creator><![CDATA[Hugo Di Francesco]]></dc:creator>
            <pubDate>Wed, 05 Sep 2018 00:00:00 GMT</pubDate>
            <atom:updated>2019-05-24T09:41:42.629Z</atom:updated>
        </item>
    </channel>
</rss>