<?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 Syed Andaleeb Roomy on Medium]]></title>
        <description><![CDATA[Stories by Syed Andaleeb Roomy on Medium]]></description>
        <link>https://medium.com/@andaleeb?source=rss-874a84b9998d------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/2*bJyfQNAMJcb8dkDfPl7q_w.jpeg</url>
            <title>Stories by Syed Andaleeb Roomy on Medium</title>
            <link>https://medium.com/@andaleeb?source=rss-874a84b9998d------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Wed, 02 Dec 2026 01:21:04 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@andaleeb/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[FFmpeg - Basic Filter Graphs]]></title>
            <link>https://medium.com/craftsmenltd/ffmpeg-basic-filter-graphs-74f287dc104e?source=rss-874a84b9998d------2</link>
            <guid isPermaLink="false">https://medium.com/p/74f287dc104e</guid>
            <category><![CDATA[video-editing-software]]></category>
            <category><![CDATA[transcoding]]></category>
            <category><![CDATA[video-transcoding]]></category>
            <category><![CDATA[media-asset-management]]></category>
            <category><![CDATA[ffmpeg]]></category>
            <dc:creator><![CDATA[Syed Andaleeb Roomy]]></dc:creator>
            <pubDate>Fri, 21 Feb 2020 16:55:51 GMT</pubDate>
            <atom:updated>2023-06-26T08:56:15.817Z</atom:updated>
            <content:encoded><![CDATA[<p><a href="https://www.ffmpeg.org/">FFmpeg</a> is considered the Swiss Army knife of video transcoding/streaming. Let’s start with some very basic examples today of what we can do with FFmpeg.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*muXu4vUEwYuTZKouY-Uwyw.png" /></figure><h4>Format conversion</h4><pre>ffmpeg -y -i input.mkv output.mp4</pre><p>In this simplest example, FFmpeg produces MP4 output from MKV input. -y denotes that we want to overwrite output.mp4 if it already exists. -i marks the input. In addition to these two, FFmpeg supports many other popular multimedia file formats, including MXF, AVI, WAV, M4A, JPG, PNG etc.</p><h4>Codec conversion</h4><pre>ffmpeg -y -i input.mkv -vcodec libx264 -acodec flac output.mkv</pre><p>It is common to use FFmpeg to transcode from one codec to another. Here, we specify the video and audio codecs with -vcodec and -acodec.</p><h4>Take only video or audio</h4><pre>ffmpeg -y -i input.mkv -map 0:v output.mp4</pre><p>-map 0:v selects the video streams from the first input (we have only one input file here anyway, marked by 0), while 0:a means the audio streams.</p><h4>Resize the video</h4><pre>ffmpeg -y -i input.mkv -filter_complex scale=720:480 output.mp4</pre><p>-filter_complex can be used to combine many filters together. Filters sit between the input and the output and make some change to the media flowing through them. Here we are using the scale filter and specifying the output width and height.</p><h4>Clipping</h4><pre>ffmpeg -y -i input.mkv -ss 30.4 -to 40.15 output.mp4</pre><p>Here, -ss and -to are used to specify the start and end times in seconds.</p><h4>Snapshot at time</h4><pre>ffmpeg -y -i input.mkv -ss 2.598 -vframes 1 output.jpg</pre><p>We can give a filename with .jpg extension, and -vframes 1 will tell FFmpeg to produce a single image at the specified time instance.</p><h4>Thumbnails at interval</h4><pre>ffmpeg -y -i input.mp4 -filter_complex &quot;fps=1/5,scale=320:180&quot; thumbnail-%03d.jpg</pre><p>The fps filter is used here to say that we need 1 frame every 5 seconds. We scale it to required dimensions and give a pattern for the thumbnail filename to be numbered as we like.</p><h4>Extract audio channels</h4><pre>ffmpeg -y -i input.mxf \<br>-filter_complex &quot;[0:a]asplit=2[a1][a2];[a1]pan=mono|c0=c0[ch1];[a2]pan=mono|c0=c1[ch2]&quot; \<br>-map [ch1] channel_1.wav \<br>-map [ch2] channel_2.wav</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*dmy-Mr1Ni_RX3t9_1ob-AA.png" /></figure><p>Getting slightly complicated now, but the graph image above should make it easier to understand. We first fork the input audio with the asplit filter into two identical branches labeled a1 and a2. Then we connect each of these to pan filters that are each set up to produce one mono channel. The first pan filter will select the first channel (c0) from a1 and the second one will select the second channel (c1)from a2, and we label the outputs from these pan filters ch1 and ch2 respectively. Lastly, we map ch1 and ch2 to produce two separate WAV files.</p><h4>Complex graphs with shared filters</h4><p>In this final example, we try to reuse common filters and produce simultaneous outputs in parallel.</p><pre>ffmpeg -y -i input.mkv \<br>-filter_complex &quot;[0:v]format=yuv420p,yadif,split=3[in1][in2][in3];[in1]scale=1920:1080[hd];[in2]scale=720:576,hflip[sd];[in3]fps=1/5,scale=320:180[thumbnails];[0:a]aresample=48000,asplit=2[a1][a2]&quot; \<br>-map [hd] -map [a1] hd.mov \<br>-map [sd] -map [a2] sd-flipped.mp4 \<br>-map [thumbnails] thumbnail-%03d.jpg</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*FxygLlhGraf3BRyUK4aNbQ.png" /></figure><p>As shown above, we apply the common operations early in the graph and try to reuse the filters whenever possible. For example, we reuse format, yadifand aresample filters for the HD and SD outputs, but do the scaling for them separately since they require different dimensions. In addition, we do a horizontal flip with hflip for the SD output only, just for fun! On the other hand, the thumbnails share some common filters (deinterlacing with yadif) with the video filters, but then needs fps and scale to adjust the frame rate and size specific to thumbnails only.</p><h4>Conclusion</h4><p>FFmpeg supports a vast collection of many other filters which can be combined to implement a lot of advanced requirements. But I hope the above examples are helpful to understand the basics and get started with this versatile and extremely powerful tool.</p><p>If you are interested to learn more, <a href="https://www.udemy.com/course/ffmpeg-the-complete-guide/?couponCode=BESTDEAL">here is a short FFmpeg course on Udemy</a>, with concepts explained with easy diagrams and step-by-step hands-on demo videos with lots of practical use cases and examples.</p><p>Happy transcoding!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=74f287dc104e" width="1" height="1" alt=""><hr><p><a href="https://medium.com/craftsmenltd/ffmpeg-basic-filter-graphs-74f287dc104e">FFmpeg - Basic Filter Graphs</a> was originally published in <a href="https://medium.com/craftsmenltd">Craftsmen — Software Maestros</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Unified Cloud Transcription Framework]]></title>
            <link>https://medium.com/craftsmenltd/unified-cloud-transcription-framework-8f8ecc983075?source=rss-874a84b9998d------2</link>
            <guid isPermaLink="false">https://medium.com/p/8f8ecc983075</guid>
            <category><![CDATA[aws]]></category>
            <category><![CDATA[transcription]]></category>
            <category><![CDATA[google-cloud-platform]]></category>
            <category><![CDATA[ibm-watson]]></category>
            <category><![CDATA[speech-recognition]]></category>
            <dc:creator><![CDATA[Syed Andaleeb Roomy]]></dc:creator>
            <pubDate>Sat, 02 Nov 2019 21:27:38 GMT</pubDate>
            <atom:updated>2019-11-02T21:52:27.101Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/918/1*rOhuKt2hbG8huJi0QGve2Q.png" /></figure><p>With the rise of machine learning and cloud computing, it looks like every major cloud provider has their own transcription (speech-to-text) service. Giants like Google, Amazon, Microsoft and IBM support a good number of languages that can be transcribed from a given audio input. It can be hard to decide which one is better for which language before we have tested them all extensively. But if we want, we can consider leaving this choice to the user if we can integrate all of the services easily.</p><p>Each of the cloud transcription services have a different API, but the ways to deal with them are mostly similar. This insight allows us to come up with a unified framework for integrating them all. This is specially true for the common use case of transcribing long audio clips. Let’s talk about what we need to handle in general for all services. The following flowchart pretty much sums it up.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/295/1*jozM-mpiYhxtpFdHj-5amA.png" /></figure><h4>Audio format</h4><p>We have seen that all the major services accept WAV, and 16-bit, single-channel, 22050 Hz WAV files have pretty good quality. So if we convert our input material to this format, we can feed it to any transcription service.</p><p>Transcoding means to convert from one format to another. In this case, we should convert the input media which can be a combination of video (H264, MPEG2 etc.) and/or compressed audio (MP3, AAC etc.), into the WAV format as described above. For transcoding, we can use FFmpeg or some other tool/service, e.g., AWS MediaConvert.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/645/1*MfEFO7-cGfAeZgCqoCbWtA.png" /></figure><h4>Media location</h4><p>Some services expect an HTTP URL to the input file, which can be done by creating a presigned URL from a bucket path. Some expect it in their own bucket (e.g., Google), in which case, we need to upload there prior to starting the job. Some services support the audio content to be posted with the API (e.g. IBM).</p><h4>Start the job</h4><p>Each service has an API to start the transcription job, by calling it via SDK or HTTP. With this API, the service usually takes -</p><ul><li>the media (presigned URL, path to file in a bucket, or posted with the API)</li><li>language code (usually in the form &lt;language&gt;-&lt;region&gt;, e.g. en-US)</li><li>other configurations: sample rate of the audio, channel count (if multichannel is supported), whether to enable speaker identification and confidence, output bucket path if needed, etc.</li></ul><p>The API returns a job ID, to be able to later query the status or results.</p><p>For example, AWS SDK has TranscribeService.startTranscriptionJob, Google has speech.v1p1beta1.SpeechClient.longRunningRecognize in their @google-cloud/speech package, and IBM has regional endpoints like <a href="https://gateway-lon.watsonplatform.net/speech-to-text/api/v1/recognitions">https://gateway-lon.watsonplatform.net/speech-to-text/api/v1/recognitions</a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/286/1*rqET8MPWhDtvWhFnvi6bBg.png" /></figure><h4>Polling</h4><p>Most providers do not support specifying a callback URL to let us know whether the job has been completed or failed. So we need to have a polling cycle of our own to periodically check the ongoing jobs. Of course, we need to maintain a map of these running jobs on our end, along with job IDs and other details.</p><h4>Get job status</h4><p>There is usually an API that allows you to get the status of a transcription job, whether it is complete, in-progress, or failed. Sometimes this even provides the progress percentage.</p><h4>Fetch job result</h4><p>The actual output of a successful job can be retrieved from the service with a separate API call, or some providers can return it as part of the same call that returns the job status (Google and IBM). AWS writes the output to a bucket that we need to read from.</p><h4>Process/convert the output</h4><p>The results returned from the services vary in structure and format, though most of them have the same information, like an array of words, with each word having a start time, end time, and confidence. We need to have a step to convert the service format into our own internal format that the rest of our system can rely on.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/448/1*vBtYyNacwBlETC92w6vQQw.png" /></figure><p>To illustrate how the formats differ from service to service, we present sample extracts from three providers.</p><p><strong>Google</strong></p><pre>[<br>   {<br>      &quot;startTime&quot;:&quot;5s&quot;,<br>      &quot;endTime&quot;:&quot;5.400s&quot;,<br>      &quot;word&quot;:&quot;what&quot;,<br>      &quot;confidence&quot;:0.9416568<br>   },<br>   {<br>      &quot;startTime&quot;:&quot;5.400s&quot;,<br>      &quot;endTime&quot;:&quot;5.500s&quot;,<br>      &quot;word&quot;:&quot;is&quot;,<br>      &quot;confidence&quot;:0.92425334<br>   },<br>   {<br>      &quot;startTime&quot;:&quot;5.500s&quot;,<br>      &quot;endTime&quot;:&quot;5.800s&quot;,<br>      &quot;word&quot;:&quot;really&quot;,<br>      &quot;confidence&quot;:0.82757676<br>   },<br>]</pre><p><strong>AWS</strong></p><pre>[<br>   {<br>      &quot;start_time&quot;:&quot;39.3&quot;,<br>      &quot;end_time&quot;:&quot;39.88&quot;,<br>      &quot;alternatives&quot;:[<br>         {<br>            &quot;confidence&quot;:&quot;1.0&quot;,<br>            &quot;content&quot;:&quot;Creatively&quot;<br>         }<br>      ],<br>      &quot;type&quot;:&quot;pronunciation&quot;<br>   },<br>   {<br>      &quot;start_time&quot;:&quot;39.88&quot;,<br>      &quot;end_time&quot;:&quot;40.26&quot;,<br>      &quot;alternatives&quot;:[<br>         {<br>            &quot;confidence&quot;:&quot;1.0&quot;,<br>            &quot;content&quot;:&quot;speaking&quot;<br>         }<br>      ],<br>      &quot;type&quot;:&quot;pronunciation&quot;<br>   },<br>   {<br>      &quot;alternatives&quot;:[<br>         {<br>            &quot;confidence&quot;:null,<br>            &quot;content&quot;:&quot;,&quot;<br>         }<br>      ],<br>      &quot;type&quot;:&quot;punctuation&quot;<br>   },</pre><p><strong>IBM</strong></p><pre>[<br>   [<br>      &quot;and&quot;,<br>      0.19,<br>      0.32<br>   ],<br>   [<br>      &quot;I&quot;,<br>      0.32,<br>      0.39<br>   ],<br>   [<br>      &quot;want&quot;,<br>      0.39,<br>      0.69<br>   ],<br>]</pre><h4>Clean up</h4><p>This step is for any housekeeping necessary, e.g., we may need to clean up the audio file uploaded to the provider’s bucket, in order to not consume space unnecessarily.</p><h4>Conclusion</h4><p>Having a unified framework really simplifies adding more transcription providers. At <a href="https://www.craftsmenltd.com/">Craftsmen</a>, we were able to successfully integrate these services following this approach —</p><ul><li><a href="https://cloud.google.com/speech-to-text">Google Cloud Speech-to-Text</a></li><li><a href="https://aws.amazon.com/transcribe/">AWS Transcribe</a></li><li><a href="https://www.ibm.com/cloud/watson-speech-to-text">IBM Watson Speech To Text</a></li><li><a href="https://docs.microsoft.com/en-us/azure/cognitive-services/speech-service/speech-to-text">Microsoft Azure Speech To Text</a></li><li><a href="https://www.zoommedia.ai/products-solutions/">Zoom Media Speech To Text</a></li><li><a href="https://www.speechmatics.com/">Speechmatics</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8f8ecc983075" width="1" height="1" alt=""><hr><p><a href="https://medium.com/craftsmenltd/unified-cloud-transcription-framework-8f8ecc983075">Unified Cloud Transcription Framework</a> was originally published in <a href="https://medium.com/craftsmenltd">Craftsmen — Software Maestros</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Rebuild Elasticsearch index without downtime]]></title>
            <link>https://medium.com/craftsmenltd/rebuild-elasticsearch-index-without-downtime-168363829ea4?source=rss-874a84b9998d------2</link>
            <guid isPermaLink="false">https://medium.com/p/168363829ea4</guid>
            <category><![CDATA[lambda]]></category>
            <category><![CDATA[reindex]]></category>
            <category><![CDATA[elasticsearch]]></category>
            <category><![CDATA[downtime]]></category>
            <category><![CDATA[aws]]></category>
            <dc:creator><![CDATA[Syed Andaleeb Roomy]]></dc:creator>
            <pubDate>Sat, 26 Oct 2019 19:20:01 GMT</pubDate>
            <atom:updated>2019-10-27T06:29:40.244Z</atom:updated>
            <content:encoded><![CDATA[<p>Elasticsearch allows us to add fast full-text searching and autocomplete features to our projects very easily. We can create an “index” in Elasticsearch and store the items we want to search as JSON documents into the index, to be able to run queries depending on different fields of the documents.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*EneEdc5IS4NPP8lPlBoVqw.png" /></figure><h4>Do we ever really need to rebuild an index?</h4><p>Yes. There are situations when this becomes unavoidable. For example, if we need to change any of the existing field mappings or analyzers. ES in general does not allow this. So you need to build a new index separate from the existing one.</p><h4>Can we keep the same index name?</h4><p>No. In order to have a smooth transition in a live system, we need to keep the old index alive while we are building the new one. So we cannot use the existing name for the new index while the old one still lives.</p><h4>What about code that refers to the old index?</h4><p>It can be a problem to update code to use the new index name every time we rebuild. So we should actually not write code that directly uses the index name for searching and indexing.</p><h4>Not use the index name? Then what?</h4><p>Alias! We should make an alias to the index, and use that in our searching/indexing code. Then we can update the alias in ES to point to the new index whenever we rebuild. This way, our code that accesses the index does not need to change every time we rebuild the index.</p><h4>How to keep an index up to date with changes to the source data?</h4><p>Usually, the ES index consists of data coming from a more persistent storage, e.g., a table in DynamoDB. We can have a trigger set up on the source database table, so that on any modifications to any row, we get a chance to run our indexing code (e.g., with AWS Lambda) for that modified row.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/988/1*IaTJDwmndzSH9rBDc9MM5g.png" /><figcaption>Trigger code keeps the index up to date with DB</figcaption></figure><h4>How do we actually (re)build an index?</h4><p>When we need to build an index, we first create the index with new mappings/analyzers and other required settings, then we go through all the rows of the table, and index each row as a document in the new ES index.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1021/1*MVNBp9dl0gc7zwh0rNK_lw.png" /><figcaption>Each DB record is indexed while rebuilding</figcaption></figure><h4>Can’t we just use the _reindex API?</h4><p>The <em>_reindex</em> API takes a snapshot of the source index and copies the documents to the destination index. It is better to have our own code for building an index from source data instead of relying on the <em>_reindex</em> API, because the old index may not have stored source documents with all the fields required for the new index.</p><h4>So when do we switch over?</h4><p>When we are done building the new index, we can update the alias to point to the new index instead of the old one. ES can do this atomically. Then we can delete the old index.</p><pre>POST /_aliases<br>{<br>  &quot;actions&quot; : [<br>    {<br>      &quot;remove&quot; : { &quot;index&quot; : &quot;current_index&quot;, &quot;alias&quot; : &quot;alias1&quot; } <br>    },<br>    {<br>      &quot;add&quot; : { &quot;index&quot; : &quot;new_index&quot;, &quot;alias&quot; : &quot;alias1&quot; }<br>    }<br>  ]<br>}</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/995/1*A_qWlL94ELmSWp8OZ9Hx2Q.png" /><figcaption>Alias points to the new index after rebuilding is done</figcaption></figure><h4>Wait, I know a case when this will not work…</h4><p>Indeed! In a live system, there can be continuous updates happening to the source data while the new index is being built. Suppose we just indexed <em>row1</em> in the new index while building it. Then before the the whole rebuild completes and we switch the alias over, <em>row1</em> gets modified by a user, as a result of which a DB trigger fires that indexes it in the old index. After the switch, when we query the new index, we will get old data for <em>row1</em>, since the new data did not get indexed in the new index.</p><h4>Can we solve this?</h4><p>We can, by using two aliases instead of one. One for queries (let’s call it <em>read_alias</em>), and one for indexing (<em>write_alias</em>). We can write our code so that all indexing happens through the <em>write_alias</em> and all queries go through the <em>read_alias</em>. Let’s consider three periods of time:</p><p><strong>Before rebuild</strong><br><em>read_alias</em>: points to <em>current_index</em><br><em>write_alias</em>: points to <em>current_index</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1011/1*toWFkasy6Zh6ELeYfb0t7A.png" /><figcaption>Before rebuild: both aliases point to the same current_index</figcaption></figure><p>All queries return current data.<br>All modifications go into <em>current_index</em>.</p><p><strong>During rebuild</strong><br><em>read_alias</em>: points to <em>current_index</em><br><em>write_alias</em>: points to <em>new_index</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1012/1*V82FggUr_t6JZgu475GcCQ.png" /><figcaption>During rebuild: read and write aliases point to different indices</figcaption></figure><p>All queries keep getting data as it existed before the rebuild, since searching code uses <em>read_alias</em>.<br>All rows, including modified ones, get indexed into the <em>new_index</em>, since both the rebuilding loop and the DB trigger use the <em>write_alias</em>.</p><p><strong>After rebuild</strong><br><em>read_alias</em>: points to <em>new_index</em><br><em>write_alias</em>: points to <em>new_index</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/996/1*dKOj8wUsyWYp65zI__i1qw.png" /><figcaption>After rebuild: both aliases point to the same new_index</figcaption></figure><p>All queries return new data, including the modifications made during rebuild.<br>All modifications go into <em>new_index</em>.</p><h4>Can we get the modified data even while rebuilding?</h4><p>It should be possible to do even that, if we make the DB trigger code index modified rows into both the indices while the rebuild is going on (i.e., while the aliases point to different indices).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1012/1*1k_qPuR9cHY6cQ9r3cIn5w.png" /><figcaption>DB trigger updates both indices during rebuild</figcaption></figure><p>At <a href="https://www.craftsmenltd.com/">Craftsmen</a>, we have been using Amazon Elasticsearch Service for a long time and this is how we have been rebuilding index without having any downtime or data loss.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=168363829ea4" width="1" height="1" alt=""><hr><p><a href="https://medium.com/craftsmenltd/rebuild-elasticsearch-index-without-downtime-168363829ea4">Rebuild Elasticsearch index without downtime</a> was originally published in <a href="https://medium.com/craftsmenltd">Craftsmen — Software Maestros</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Building a cross-platform background service in Node.js]]></title>
            <link>https://medium.com/craftsmenltd/building-a-cross-platform-background-service-in-node-js-791cfcd3be60?source=rss-874a84b9998d------2</link>
            <guid isPermaLink="false">https://medium.com/p/791cfcd3be60</guid>
            <category><![CDATA[background-service]]></category>
            <category><![CDATA[nodejs]]></category>
            <category><![CDATA[cross-platform]]></category>
            <dc:creator><![CDATA[Syed Andaleeb Roomy]]></dc:creator>
            <pubDate>Sun, 14 Apr 2019 13:24:31 GMT</pubDate>
            <atom:updated>2019-04-14T14:05:15.060Z</atom:updated>
            <content:encoded><![CDATA[<p>We are living in an era where you can use JavaScript to write almost any part of an application: whether it is the UI that runs in the browser or mobile, or the service/lambda that does the heavy lifting in the cloud, or even beautiful desktop applications like Slack and Visual Studio Code.</p><p>In this article, we will discuss how we can build a background service in Node.js that can run across Windows, Linux and macOS.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/474/1*7Ic6TFEb_OrjLOGU2oGhsA.jpeg" /></figure><h3>What is a background service?</h3><p>A background service (aka daemon) is an executable program that usually starts automatically on boot and keeps running without a UI. For any executable to be a service, it must conform to some rules that the OS expects from a service, like responding to start/stop commands that the OS service runner sends.</p><h4>Executable? You mean the JavaScript source file?</h4><p>Not really. We want our service to be a single binary executable without having to rely on the Node.js runtime being installed on the system it will run on. In order to compile this binary, we can use the <a href="https://www.npmjs.com/package/pkg"><strong>pkg</strong></a><strong> </strong>module. But there is a catch: pkg does not support packaging <em>native addons</em> (.node files) inside the executable. So, as we depend on such a module (os-service, as described below), we will need to manually copy the .node file(s) to the output directory in our build script —</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/877/1*NK5-1pznyUZyQ7XjKulETA.png" /></figure><pre># PLATFORM should be win, linux, or macos<br>TARGETS=&quot;--targets node10-$PLATFORM-x64&quot;<br>npx pkg . --out-path $OUT_PACKAGE_DIR $TARGETS<br>cp node_modules/os-service/build/Release/service.node $OUT_PACKAGE_DIR/</pre><p>It is important to note that the build for each platform needs to be done from that platform, as the native addons are different for each platform.</p><p>In the following section, we discuss the code to install, start, stop, and uninstall a service. This code can be part of the single service executable, or a separate tool just for doing these tasks.</p><h4>How to know which platform you are running on?</h4><p>Even though some modules take care of platform specific implementation details, there are still situations when you will need to know whether you are running on Windows, Linux, or macOS. The process variable contains the name of the platform, e.g. —</p><pre>function isWin() {<br>  return process.platform === &quot;win32&quot;;<br>}</pre><pre>function isMac() {<br>  return process.platform === &quot;darwin&quot;;<br>}</pre><h4>Installing the service</h4><p><a href="https://www.npmjs.com/package/os-service"><strong>os-service</strong></a> is a module that takes care of most of the OS-specific stuff needed to behave as a service.</p><pre>const service = require (&quot;os-service&quot;);</pre><pre>service.add(<br>  SERVICE_NAME,<br>  {<br>    displayName,<br>    programPath,<br>    programArgs,<br>    username, // the username to run the service as<br>    password<br>  },<br>  function(error: any) {<br>    if (error) {<br>      reject(error);<br>    } else {<br>      resolve();<br>    }<br>  }<br>);</pre><p>Though os-service works nicely for Windows and Linux, it does not handle macOS. For that, we need to save a plist file describing a <em>LaunchDaemon</em> in `/Library/LaunchDaemons/${SERVICE_NAME}.plist`. This is a special XML file containing the service name, path and arguments to the executable. We also need to set the RunAtLoad key to true in order to start it at boot. Correct permissions must be set for macOS to launch the service.</p><pre>const cp = require(&#39;child_process&#39;)</pre><pre>cp.execSync(`sudo mkdir -p ${path.dirname(filePath)}`);<br>cp.execSync(`sudo touch ${filePath}`);<br>cp.execSync(`sudo chown root:wheel ${filePath}`);<br>cp.execSync(`sudo chmod ${permissions} ${filePath}`);<br>const command = `sudo sh -c ‘cat &gt; ${filePath}’`;<br>cp.execSync(command, { input: fileContent });</pre><p>Sample plist file content:</p><pre>&lt;?xml version=&quot;1.0&quot; encoding=&quot;UTF-8&quot;?&gt;<br>&lt;!DOCTYPE plist PUBLIC &quot;-//Apple Computer//DTD PLIST 1.0//EN&quot; &quot;<a href="http://www.apple.com/DTDs/PropertyList-1.0.dtd">http://www.apple.com/DTDs/PropertyList-1.0.dtd</a>&quot;&gt;<br>&lt;plist version=&quot;1.0&quot;&gt;<br>  &lt;dict&gt;<br>    &lt;key&gt;Label&lt;/key&gt;<br>    &lt;string&gt;${SERVICE_NAME}&lt;/string&gt;<br>    &lt;key&gt;Program&lt;/key&gt;<br>    &lt;string&gt;${EXE_PATH}&lt;/string&gt;<br>    &lt;key&gt;ProgramArguments&lt;/key&gt;<br>    &lt;array&gt;<br>      &lt;string&gt;${EXE_PATH}&lt;/string&gt;<br>      &lt;string&gt;run&lt;/string&gt;<br>      &lt;string&gt;--config-file&lt;/string&gt;<br>      &lt;string&gt;${DEFAULT_CONFIG_FILE_PATH}&lt;/string&gt;<br>    &lt;/array&gt;<br>    &lt;key&gt;RunAtLoad&lt;/key&gt;<br>    &lt;true/&gt;<br>    &lt;key&gt;KeepAlive&lt;/key&gt;<br>    &lt;true/&gt;<br>  &lt;/dict&gt;<br>&lt;/plist&gt;</pre><h4>Starting the service</h4><p>Once the service is installed, you can start the service with different platform specific commands like shown here —</p><pre>if (isWin()) {<br>  cp.execSync(`net start ${SERVICE_NAME}`);<br>} else if (isMac()) {<br>  cp.execSync(`sudo launchctl load ${LAUNCHD_PLIST_PATH}`);<br>} else {<br>  cp.execSync(`service ${SERVICE_NAME} start`);<br>}</pre><h4>Stopping the service</h4><p>Similar to above —</p><pre>if (isWin()) {<br>  cp.execSync(`net stop ${SERVICE_NAME}`);<br>} else if (isMac()) {<br>  cp.execSync(`sudo launchctl unload ${LAUNCHD_PLIST_PATH}`);<br>} else {<br>  cp.execSync(`service ${SERVICE_NAME} stop`);<br>}</pre><h4>Uninstalling the service</h4><p>In macOS, we need to remove the LaunchDaemon plist file. For other platforms, we can just use remove from os-service. Before removing the service, it is better to stop it if it is currently running, as otherwise it can throw an error.</p><pre>if (isMac()) {<br>  await removeFileAsRoot(LAUNCHD_PLIST_PATH);<br>  resolve();<br>  return;<br>}</pre><pre>service.remove(SERVICE_NAME,<br>  function(error: any) {<br>    if (error) {<br>      logger.info(`Please make sure to stop the service before removing it`);<br>      reject(error);<br>    } else {<br>      resolve();<br>    }<br>  }<br>);</pre><p>That’s it folks! Hope this will help you write your awesome service entirely in Node.js, without writing a single line of code in any other traditional technologies.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=791cfcd3be60" width="1" height="1" alt=""><hr><p><a href="https://medium.com/craftsmenltd/building-a-cross-platform-background-service-in-node-js-791cfcd3be60">Building a cross-platform background service in Node.js</a> was originally published in <a href="https://medium.com/craftsmenltd">Craftsmen — Software Maestros</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>