<?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[codesight - Medium]]></title>
        <description><![CDATA[The development blog for codesight where we explore javascript, typescript and web technology - Medium]]></description>
        <link>https://medium.com/codesight?source=rss----37286c7be563---4</link>
        <image>
            <url>https://cdn-images-1.medium.com/proxy/1*TGH72Nnw24QL3iV9IOm4VA.png</url>
            <title>codesight - Medium</title>
            <link>https://medium.com/codesight?source=rss----37286c7be563---4</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Tue, 01 Dec 2026 16:08:47 GMT</lastBuildDate>
        <atom:link href="https://medium.com/feed/codesight" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Easy machine learning with MindsDB]]></title>
            <link>https://medium.com/codesight/easy-machine-learning-with-mindsdb-664e27c974f9?source=rss----37286c7be563---4</link>
            <guid isPermaLink="false">https://medium.com/p/664e27c974f9</guid>
            <category><![CDATA[coding]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[development]]></category>
            <category><![CDATA[mindsdb]]></category>
            <dc:creator><![CDATA[Liron Navon]]></dc:creator>
            <pubDate>Thu, 01 Apr 2021 11:28:46 GMT</pubDate>
            <atom:updated>2021-04-01T13:26:46.294Z</atom:updated>
            <content:encoded><![CDATA[<h4>A tutorial for working with <a href="https://mindsdb.com/">MindsDB</a> and using it to understand machine learning concepts.</h4><p>Machine learning is pretty much everywhere now, almost every company nowadays accumulates giant amounts of data and would like to extract as much information from it as possible to enhance its business and customer satisfaction, Facebook and Google try to match the perfect ads to you, Netflix tries to predict what is the next movie you would like to watch, and Spotify tries to find music that you would love.</p><p>Machine learning is not easy, it requires some knowledge to extract data, add missing information, find what pieces of data correlates to your predictions and create a prediction algorithm based on different variables — that means you need to hire machine learning experts and have the extra infrastructure for it, some tools are making it easier like Firebase’s auto ML, but <a href="https://mindsdb.com/">MindsDB</a> is the only tool that does that and is open source, and is connecting directly to your database to make it easy and efficient to make predictions.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*DnEX9Ha2iOzCmCeYRhNd4w.jpeg" /><figcaption>MindsDB background image taken from their <a href="https://www.linkedin.com/company/mindsdb/">linkedin page</a></figcaption></figure><p>In this example <a href="https://mindsdb.com/">MindsDB</a> will be working as a middleman between your server and the database, you can run it using docker and it will provide you with GUI and a rest API to communicate with the database to make predictions, it keeps the trained models and the metadata it needs in your database in a separate table.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/568/1*yeCxPy0aHrSj9KGqf76u8Q.jpeg" /></figure><h3>Getting started</h3><p>In this tutorial, we will be completely framework agnostic in work only with the GUI and the database, but I will make other posts demonstrating the work with the API in future posts.</p><p>We can make predictions on different, more complicated data, but in this post, we will make predictions using the <a href="https://www.kaggle.com/arshid/iris-flower-dataset">Iris dataset</a>, if you ever learned ML you probably read a tutorial with this dataset, it’s very common since it is very simple to understand.<br>The Iris dataset defines 3 species of the Iris flower, with information about their petal and sepal sizes, these measurements have been taken from 150 different flowers, so we have 5 columns and 150 rows of data, we are going to use this information to categorize the flower species, given the petal and sepal measurements.</p><p>For example, we want to say that if an Iris flower has a sepal width of 3.5, a sepal length of 5.1, and petal length of 1.4, and a petal width of 0.2 -&gt; that Iris is Iris-setosa.</p><p>Let’s get started, we will have to follow a few steps first, we need to create a database, fill it with the Iris dataset, run MindsDB, connect it to the database, and then we can make predictions, it’s pretty simple, so let’s start.</p><h4>1. Run a database and fill it with data</h4><p>MindsDB supports different databases including MongoDB, MariaDB, PostgreSQL, MySQL, and more… you can choose the database you&#39;re comfortable with, but for the sake of this post, I will use PostgreSQL.</p><p>So I’m running PostgreSQL locally and filling it with the <a href="https://www.kaggle.com/arshid/iris-flower-dataset">Iris dataset</a>, I’m using the pre-made SQL command from <a href="https://gist.github.com/faustofjunqueira/ba97008616148653a9c633c066edaba9">this gist</a> to populate the database quickly, your database should look somewhat like this.</p><ul><li>You can skip this step and use the <a href="https://www.kaggle.com/arshid/iris-flower-dataset">Iris dataset CSV file</a> directly if you just want to play with MindsDB, by using the upload button on the GUI, this CSV will be your dataset.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*DYS-yVgzUcxbV2BO3ftBmg.png" /><figcaption>Example of a database filled with the Iris dataset (using PgAdmin4)</figcaption></figure><h4>2. Run MindsDB</h4><p>I’m running MindsDB as a docker container, but of course, you can decide to run it locally, <a href="https://docs.mindsdb.com/">the installation guide is here</a>.</p><p>I’m expecting you already have docker running on your machine, if not <a href="https://www.docker.com/products/docker-desktop">just install and run it</a>, once it’s running run these shell commands:</p><pre># pull the image<br>$ docker pull mindsdb/mindsdb</pre><pre># run the image and expose port 47334<br>$ docker run -p 47334:47334 mindsdb/mindsdb</pre><p>After you run the image, you can go to <a href="http://localhost:47334/">http://localhost:47334</a> o access the MindsDB GUI, it should look something like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Vzem-voyDW7AewrKH54EYw.png" /><figcaption>The dataset view</figcaption></figure><h4>3. Create a dataset</h4><p>I will be connecting my PostresQL to MindsDB by clicking the database icon and then “add database”:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*77nSO2wnNSdMffMtVuyQMQ.png" /><figcaption>I’m using <a href="https://ngrok.com/">Ngrok</a> to create a TCP tunnel, this allows me to run the database locally and call it from the docker image, that’s why the host is “0.tcp.ngrok.io”.</figcaption></figure><p>now that our database is connected we can clock “New Dataset” and extract the dataset using an SQL query, in my case I want all the columns from the dataset and all the rows, so a simple SELECT * FROM iris is enough for us.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*jihaSbabStw7OI0NP8UL9w.png" /><figcaption>Datasource modal</figcaption></figure><p>Then we can go to the dataset and see two buttons <strong>Overview</strong> where you can see your dataset in a table, and <strong>Quality</strong> where you can assess the <a href="https://en.wikipedia.org/wiki/Data_quality">data quality</a>, let’s take a look at the quality view:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*q9q5HZeRX18QjivtdfJGEw.png" /><figcaption>Data quality view for sepal length</figcaption></figure><p>Here we can see the data is really good, no missing values are here, in many cases you might be missing some information, in those cases, MindsDB will fill these missing values with the average values for you, the more data is missing or inconsistent, the worse your dataset is, the less accurate our machine learning algorithm will be.</p><h4>4. Train a predictor</h4><p>Now we can create a predictor by clicking “predictors” and then “train”, decide what you would like to predict, and click “train”.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*O8I12xhhcH7_sLQ6X9RsIg.png" /><figcaption>Predictor training view</figcaption></figure><p>* <strong>Advanced Mode </strong>— you can use the advanced mode to make some changes to the predictor, for example, you can use the time-series mode, group items, and change the sample margin, we currently have a pretty simple problem and it’s a simple post, so we won&#39;t use it — I will include this in a future post.</p><p>We can click “Preview” on the trained predictor to see some information about it and I’ll explain some basic machine learning concepts, as you see in “dataset splitting and usage”, our data is being divided and used as <a href="https://lhessani-sajid.medium.com/what-is-the-difference-between-training-and-test-dataset-91308080a4e8#:~:text=In%20a%20dataset%2C%20a%20training,the%20test%20(validation)%20set.">Training data and Test data</a>, MindsDB selects at random around 120 rows to train the machine learning model, and around 30 rows to test the model, this helps it to determine the accuracy f the predictor — it’s common to use 20% of the data for testing and 80&amp; for training ML models.</p><p>The second thing to watch for is the column importance, we might want to throw every piece of information we have into a machine learning model, but not all the information is useful for every prediction, let’s say we also have the height of the flower or its color, it might be completely useless when determining it’s species, in this case, we can make changes to the data or decide not to use all the columns next time — which will speed up the training time and improve accuracy.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*1fGKKA4SxvNKYfYiXIGbvw.png" /><figcaption>Predictor accuracy and column importance chart</figcaption></figure><p>The next piece of information we get is the <a href="https://www.dataschool.io/simple-guide-to-confusion-matrix-terminology/#:~:text=A%20confusion%20matrix%20is%20a,related%20terminology%20can%20be%20confusing.">confusion matrix</a>, confusion matrix allows us to see how accurate the test data and the training data are for each prediction (each iris species in ur case), that is the “<a href="https://developers.google.com/machine-learning/crash-course/classification/accuracy">100% accuracy</a>” we saw in the last picture, it means that when looking in the test data and running it against the model, it predicted correctly 100% of the flowers. Do notice, 100% accuracy is very rare, and it is mostly determined by the quality and size of the data we have.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*prh9Ry8_eK37pFt0k5Q30A.png" /><figcaption>The confusion matrix chart</figcaption></figure><h4>5. Make a prediction</h4><p>This is the last step, we simply need to use our predictor, to determine how to classify a new Iris flower we just found, we can go to “query” and click “new query”, fill in the data we got from a new flower we found, and let our predictor determine which species it is.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*hKs9pidQm_B9Pyjz7vnh5w.png" /><figcaption>New query modal</figcaption></figure><p>Now we can see the prediction, we have predicted that a flower with these measurements is Iris-setosa, and we are 81% sure about it, the bigger our dataset is, the more sure we will be about the predictions we make (and I pretty much used random numbers for this prediction).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*A8_ha_lrl0-1jIK8M8araQ.png" /><figcaption>Query result view</figcaption></figure><h4>What next</h4><p>We have created and trained a machine learning model (predictor) and used it to make a prediction, all this can take just a minute or two with MindsDB, As you can see MindsDB is really easy and simple to use.</p><p>The next step will be to make API calls to MindsDB to automate the extraction of the dataset, the training of the model, and to make predictions, we will be doing this in different languages in a future post.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=664e27c974f9" width="1" height="1" alt=""><hr><p><a href="https://medium.com/codesight/easy-machine-learning-with-mindsdb-664e27c974f9">Easy machine learning with MindsDB</a> was originally published in <a href="https://medium.com/codesight">codesight</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Getting started with Web Assembly and Go for frontend developers.]]></title>
            <link>https://medium.com/codesight/getting-started-with-web-assembly-and-go-for-frontend-developers-5e1831f0a18b?source=rss----37286c7be563---4</link>
            <guid isPermaLink="false">https://medium.com/p/5e1831f0a18b</guid>
            <category><![CDATA[go]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[webassembly]]></category>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[golang]]></category>
            <dc:creator><![CDATA[Liron Navon]]></dc:creator>
            <pubDate>Mon, 27 May 2019 07:49:50 GMT</pubDate>
            <atom:updated>2019-05-31T18:16:11.064Z</atom:updated>
            <content:encoded><![CDATA[<p>Web assembly is picking up and is now supported in <a href="https://caniuse.com/#feat=wasm">most modern browsers (85%)</a>, and it’s a good time to get started if you haven’t yet, get started with Go (Golang for search engines) is really easy, and no go experience is required for this tutorial — you can read more about how WASM works and why use it <a href="https://blog.logrocket.com/webassembly-how-and-why-559b7f96cd71">here</a>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/612/1*igmwlOsICf5E1oNVyUZhoQ.png" /></figure><p>To get started we should first have GO installed, you can check the instructions <a href="https://golang.org/doc/install">here</a>.<br>Once we have Go installed, we need to create a new directory, and in it create a few initial files (you can simply <a href="https://github.com/liron-navon/go-wasm-tutorial">clone the repo</a>):</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/2da6f8072e9a039c25a00483ea32342f/href">https://medium.com/media/2da6f8072e9a039c25a00483ea32342f/href</a></iframe><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/6a257db92739547697d977fbc5bb7468/href">https://medium.com/media/6a257db92739547697d977fbc5bb7468/href</a></iframe><p>We use the <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/WebAssembly/instantiateStreaming">WebAssembly.instantiateStreaming</a> function to initiate the wasm code, and use the go loader to run our wasm code.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c7cee4e4b911eed6c75d73c2f3825bb9/href">https://medium.com/media/c7cee4e4b911eed6c75d73c2f3825bb9/href</a></iframe><p>Our main.go file is simple: we import the fmt package which has similar functionality to console.log (for our use), and by default, it will print to our console, and we have a function named main, every Go project starts with the main function, and once the code is loaded through wasm, this function will run and print “Hello, WebAssembly!” to the console.</p><p>Now that we have the initial files, we need to get the “wasm_exec.js” file, which will allow us to load the wasm code for go (this is what gives us the Go class we use in the index.html file), we can get it by copying from go’s root files.</p><pre>cp &quot;$(go env GOROOT)/misc/wasm/wasm_exec.js&quot; .</pre><p>Now we can compile or code from main.go , we compile to js runtime (GOOS) and use the wasm architecture (GARCH), and output the resault into a main.wasmfile.</p><pre>GOOS=js GOARCH=wasm go build -o main.wasm</pre><p>We should now have a file named main.wasm, this is the file containing the web assembly code that we will run.</p><p>Now we can use any HTTP server to run our code, I use <a href="https://www.npmjs.com/package/http-server">http-server</a> for it, and we should see our string logged in the console.</p><h3>Named functions</h3><p>Now that we have a simple wasm code working, we can get started with named functions, we want to export some functions from our Go code so we can use them in our javascript code.</p><p>To bind our Go code to the JS runtime, Go provides us a package <a href="https://golang.org/pkg/syscall/js/">syscall/js </a>which we can import and use to bind a function to the global window.<br>as you can see, our import exposes a variable named js and we can get the Global which is the window (for browsers), and we can set a function with Set, the function is called “add”, and we use the js.NewCallback to turn our Go function to javascript Function.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/9dfd61845ce2b822e45fe345999f98a3/href">https://medium.com/media/9dfd61845ce2b822e45fe345999f98a3/href</a></iframe><p>Ignore the lines with the done for now, they are used here to prevent the Go program from exiting (by creating a <a href="https://tour.golang.org/concurrency/2">Go channel</a> and waiting for it to receive data).</p><p>Let&#39;s implement the function named “add” in our Go code, which will accept two numbers and add them up:</p><pre>// accept any number of javascript values as arguments<br>func add(args []js.Value) {<br>  <br>  // convert the JS values to Integers (numbers)<br>  var a = args[0].Int()<br>  var b = args[1].Int()</pre><pre>  // print the sum of the numbers<br>  fmt.Println(a + b)<br>}</pre><p>So our full main.go now looks like this:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/006ca46774c1c936f3425fbb02f1226a/href">https://medium.com/media/006ca46774c1c936f3425fbb02f1226a/href</a></iframe><p>Now we can call the function window.add(1,2) in our javascript code.</p><h3>Passing values from Go to Javascript</h3><p>That’s nice, and that’s what most tutorials will cover, but we want to get sum instead of printing it to the console.</p><p>Since js.NewCallback interface doesn’t allow us to return values, and the functions are called asynchronously, we can use good old callbacks, and later use them as promises, this is a go function we will use to call the callback, it accepts an array of js values, a value to return (“interface{}” basically means any type), and an error (if any exist).</p><pre>func execCallback(args []js.Value, value interface{}, e error) {<br>   // get the last value<br>   var last = args[len(args) - 1]</pre><pre>   // if the last argument is a function, invoke it<br>   if last.Type() == js.TypeFunction {<br>     last.Invoke(e, value)<br>   } else {<br>     println(&quot;no callback&quot;)<br>  }<br>}</pre><p>And now our main.go file will look like this:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/034de6f3c88caaaa21c9ffaad475fe15/href">https://medium.com/media/034de6f3c88caaaa21c9ffaad475fe15/href</a></iframe><p>And when we rebuild it and reload the web page, we can make a call to add like this:</p><pre>add(5, 10, (sum, error) =&gt; console.log(sum));</pre><p>We can turn this call into a promise to make things simpler for us, this is our new js code:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/0f41c6bd3faf8d97288a348de3700bbf/href">https://medium.com/media/0f41c6bd3faf8d97288a348de3700bbf/href</a></iframe><h3>Cleaning the global scope</h3><p>We are ending up with functions that are bounded to the global scope, let’s bind them to a local scope (any object) instead.</p><p>I added a function named register which we will have to call with an object, and assign it to a javascript function named __wasm_main, we will bind all other functions to this object and use them from there, meaning we are causing less pollution to the global scope.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/d402b3bf9a6a0eee6b2f693799e3078f/href">https://medium.com/media/d402b3bf9a6a0eee6b2f693799e3078f/href</a></iframe><p>And now to change our js code a little:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/cc18e1c1de459cf2e32493f3a046957e/href">https://medium.com/media/cc18e1c1de459cf2e32493f3a046957e/href</a></iframe><h3>What’s next?</h3><p>There are a few Webpack WASM loaders for Go, and you can use those to add Go into your frontend workflow, also there is a very interesting frontend framework that is very similar to Vue, named <a href="https://www.vugu.org/">vugu</a> which allows you to create wonderful UI experience using WASM and Go. If you do not know Go and wish to keep exploring it, I recommend doing the <a href="https://tour.golang.org/welcome/1">tour of go</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5e1831f0a18b" width="1" height="1" alt=""><hr><p><a href="https://medium.com/codesight/getting-started-with-web-assembly-and-go-for-frontend-developers-5e1831f0a18b">Getting started with Web Assembly and Go for frontend developers.</a> was originally published in <a href="https://medium.com/codesight">codesight</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Creating an embedded browser with React-Native]]></title>
            <link>https://medium.com/codesight/creating-an-embedded-browser-with-react-native-aea42b54740?source=rss----37286c7be563---4</link>
            <guid isPermaLink="false">https://medium.com/p/aea42b54740</guid>
            <category><![CDATA[react]]></category>
            <category><![CDATA[development]]></category>
            <category><![CDATA[webview]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[react-native]]></category>
            <dc:creator><![CDATA[Liron Navon]]></dc:creator>
            <pubDate>Mon, 04 Mar 2019 01:46:11 GMT</pubDate>
            <atom:updated>2019-11-15T09:13:52.280Z</atom:updated>
            <content:encoded><![CDATA[<h3>Creating an embedded browser with React-Native using react-native-webview</h3><p>In this tutorial, I will show you how to add an embedded browser into your RN mobile app, just like facebook does in their app.<br>It started as a question in one of the react native groups I’m a part of, the question was basically:</p><blockquote>How can I embed chromium in a React Native application?</blockquote><p>The question became a conversation about the implementation, And it came to me that people have the wrong ideas about how React Native works, and specifically about the implementations of WebView and UIWebview or WKWebView.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*HWYxqb_DXBPUEgh34tmv4A.jpeg" /><figcaption>Photo by <a href="https://www.pexels.com/@fotios-photos?utm_content=attributionCopyText&amp;utm_medium=referral&amp;utm_source=pexels">Lisa Fotios</a> from <a href="https://www.pexels.com/photo/white-turned-on-samsung-android-smartphone-192273/?utm_content=attributionCopyText&amp;utm_medium=referral&amp;utm_source=pexels">Pexels</a></figcaption></figure><p>Webview is actually a full blown browser implementation, for android it would be chromium, and depends on the Android version, it will be a different version of chromium. For Android, it’s actually possible to create a new browser engine from scratch (<a href="https://wiki.mozilla.org/Mobile/GeckoView">like Firefox does with Gecko</a>).<br>But apple restricts the browser to only be their implementation of mobile safari, so yea, even <a href="https://blog.chromium.org/2016/01/a-faster-more-stable-chrome-on-ios.html"><strong>Chrome for IOS is actually WKWebView With extra features</strong></a><strong>, </strong>chrome does have a lot of optimizations and of course google’s web layer.</p><p>In short, this is what each WebView type means:</p><p><a href="https://developer.android.com/reference/android/webkit/WebView">Android WebView</a> — WebView objects allow you to display web content as part of your activity layout, but lack some of the features of fully-developed browsers. It is based on chromium.</p><p><a href="https://developer.apple.com/documentation/webkit/wkwebview">IOS WKWebview </a>— An object that displays interactive web content, such as for an in-app browser. It was introduced in IOS 8 and is the new standard WebView (it is the default for IOS when using react-native-webview).</p><p><a href="https://developer.apple.com/documentation/uikit/uiwebview">IOS UIWebview</a> — A view that embeds web content in your app. It’s a standard WebView from the UIKit, for most use cases you should consider it as the legacy WebView — it has support for legacy features that are not supported in WKWebview.</p><h3>Getting started</h3><p><a href="https://github.com/liron-navon/react-native-simple-browser">You can check the full code in the git repository.</a></p><p>We are going to go over a basic browser implementation using <a href="https://github.com/react-native-community/react-native-webview">react-native-webview</a>, it is able to: use the search bar to go to a website or search using any search engine, go back/forward, refresh, use incognito and inject javascript which can communicate back with the React Native code, it looks like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*oF3HK-gCipPreXiUDKSa_g.png" /></figure><p>Hopefully, you already have React native, expo and Android/IOS development environment setup, if not, <a href="https://facebook.github.io/react-native/">just follow the official getting started</a>.</p><pre>expo init RNBrowser # select the blank option<br>cd RNBrowser</pre><pre># Eject expo, since we will use native components<br>npm run eject # select the expo kit option</pre><pre># Install and link the webview component<br>react-native install react-native-webview</pre><p>Now You will need to go into either <a href="https://developer.apple.com/xcode/">XCode</a>(for IOS) or <a href="https://developer.android.com/studio/?gclid=Cj0KCQiAk-7jBRD9ARIsAEy8mh78-UOQbfUiyldXThKCBin8WfUGpWIG1w_izil7PvSi0iYZv_rSMF4aAgIMEALw_wcB">Android Studio</a>(for Android) and build the project from there, this can take a few minutes.<br>Now you can run the app normally using:</p><pre>npm start</pre><p>Now we can create a new component, we can call it Browser.js, and change App.js to include it.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/32a8a0a6b062f343883a6d5e30067da8/href">https://medium.com/media/32a8a0a6b062f343883a6d5e30067da8/href</a></iframe><h4>Setting up the browser</h4><p>Now we can create the browser, you can see the full code in the git repository, but we will go over different parts here, let’s start off by loading a URL:</p><pre><em>import </em>{WebView} <em>from </em>&quot;react-native-webview&quot;;</pre><pre># And render<br>&lt;WebView <em>source={{ uri: &#39;</em><a href="https://medium.com/">https://medium.com</a><em>&#39;}}</em>/&gt;</pre><h4>Setting up search engines and search addresses</h4><p>That’s enough to display a single page, and we can allow the user to navigate to different pages by adding a <a href="https://facebook.github.io/react-native/docs/textinput">TextInput</a>, and a button to look up the website.<br>Since users are lazy, we can use a function to upgrade the URL from simple words, simply put, it will take the text check if it is a valid URL, or if it looks like a URL and upgrade it to HTTPS (the WebView will degrade to HTTP if no HTTPS was hit.), and if it doesn’t look like a URL, we will simply use some search engine to look it up.</p><pre><em>// functions to search using different engines<br>const </em>searchEngines = {<br>    &#39;google&#39;: (uri) =&gt; `https://www.google.com/search?q=${uri}`,<br>    &#39;duckduckgo&#39;: (uri) =&gt; `https://duckduckgo.com/?q=${uri}`,<br>    &#39;bing&#39;: (uri) =&gt; `https://www.bing.com/search?q=${uri}`<br>};<br><br><em>// upgrade the url to make it easier for the user:<br>//<br>// https://www.facebook.com =&gt; https://www.facebook.com<br>// facebook.com =&gt; https://www.facebook.com<br>// facebook =&gt; https://www.google.com/search?q=facebook<br>function </em>upgradeURL(uri, searchEngine = &#39;google&#39;) {<br>    <em>const </em>isURL = uri.split(&#39; &#39;).length === 1 &amp;&amp; uri.includes(&#39;.&#39;);<br>    <em>if </em>(isURL) {<br>        <em>if </em>(!uri.startsWith(&#39;http&#39;)) {<br>            <em>return </em>&#39;https://www.&#39; + uri;<br>        }<br>        <em>return </em>uri;<br>    }<br>    <em>// search for the text in the search engine<br>    const </em>encodedURI = encodeURI(uri);<br>    <em>return </em>searchEngines[searchEngine](encodedURI);<br>}</pre><p>That feature exists pretty much in any browser.</p><h4>Setting navigation</h4><p>Now we need another feature, we would like to allow the user to go forward and back, that’s pretty simple using the ref for the WebView, but for the UI we would also want to know if he can or can’t go back/forward.<br>We get the state of the browser when it changes page:</p><pre>// create a method to handle navigation for the component<br>onNavigationStateChange = (navState) =&gt; {<br>    <em>const </em>{canGoForward, canGoBack, title} = navState;<br>    <em>this</em>.setState({<br>        canGoForward,<br>        canGoBack,<br>        title<br>    })<br>};</pre><pre>// render<br>&lt;WebView<br>    <em>ref</em>={<em>this</em>.setBrowserRef}<br>    <em>source</em>={{ uri: currentURL}}<br>    <em>onNavigationStateChange</em>={<em>this</em>.onNavigationStateChange}<br>/&gt;</pre><p>Now we can use the ref for simple operations:</p><pre><em>// go to the next page<br></em>goForward = () =&gt; {<br>    <em>if </em>(browserRef &amp;&amp; <em>this</em>.state.canGoForward) {<br>        browserRef.goForward();<br>    }<br>};<br><br><em>// go back to the last page<br></em>goBack = () =&gt; {<br>    <em>if </em>(browserRef &amp;&amp; <em>this</em>.state.canGoBack) {<br>        browserRef.goBack();<br>    }<br>};<br><br><em>// reload the page<br></em>reload = () =&gt; {<br>    <em>if </em>(browserRef) {<br>        browserRef.reload();<br>    }<br>};</pre><h4>Setting incognito mode</h4><p>For IOS we can simply pass a flag for incognito, but for Android, we can do it manually, in it’s simplest form incognito means we won’t cache pages, allow cookies and storage and location.</p><pre># our state<br>state = {<br>    currentURL: url,<br>    urlText: url,<br>    title: &#39;&#39;,<br>    canGoForward: <em>false</em>,<br>    canGoBack: <em>false</em>,<br>    incognito: <em>false</em>,<br>    config: {<br>        allowStorage: <em>true</em>,<br>        allowJavascript: <em>true</em>,<br>        allowCookies: <em>true</em>,<br>        allowLocation: <em>true</em>,<br>        allowCaching: <em>true</em>,<br>        defaultSearchEngine: &#39;google&#39;<br>    }<br>};</pre><pre># toggle incognito mode<br>toggleIncognito = () =&gt; {<br>    <em>this</em>.setState({<br>        incognito: !<em>this</em>.state.incognito<br>    });<br>    <em>this</em>.reload()<br>};</pre><pre># get the configurations<br>get config() {<br>    <em>const </em>{incognito, config} = <em>this</em>.state;<br>    <em>if </em>(incognito) {<br>        <em>return </em>{<br>            ...config,<br>            allowStorage: <em>false</em>,<br>            allowCookies: <em>false</em>,<br>            allowLocation: <em>false</em>,<br>            allowCaching: <em>false</em>,<br>        }<br>    }<br>    <em>return </em>config;<br>}</pre><pre># render<br>&lt;WebView<br>    <em>source</em>={{uri: currentURL}}<br>    <em>thirdPartyCookiesEnabled</em>={this.config.allowCookies}<br>    <em>domStorageEnabled</em>={this.config.allowStorage}<br>    <em>javaScriptEnabled</em>={this.config.allowJavascript}<br>    <em>geolocationEnabled</em>={this.config.allowLocation}<br>    <em>cacheEnabled</em>={this.config.allowCaching}<br>/&gt;</pre><h4>Injecting Javascript</h4><p>Sometimes we would like to track the user or add functionality to the browser like password management or simply track the browser, it’s pretty simple to do so:</p><pre># Create some javascript to inject<br><em>const </em>injectedJavaScript = `<br>      alert(&#39;Injected javascript!&#39;);<br>      window.ReactNativeWebView.postMessage(&#39;injected javascript works!&#39;);<br>      true; // note: this is required, or you&#39;ll sometimes get silent failures   <br>`;</pre><pre># Set the script in the webview and add a listener to onMessage<br>&lt;WebView<br>    <em>onMessage</em>={<em>this</em>.onBrowserMessage}<br>    <em>injectedJavaScript</em>={javascriptCode}<br>/&gt;</pre><pre># Do something with the message<br>onBrowserMessage = (event) =&gt; {<br>    console.log(event.nativeEvent.data);<br>};</pre><p>Or we can inject more dynamically using the ref:</p><pre>browserRef.injectJavaScript(javascriptCode);</pre><h4>Blocking pages</h4><p>Maybe you would like to automatically block ad providers to prevent annoying ads, you can use a tool like <a href="https://easylist.to/index.html">EasyList</a> for that, and set a filter for the requests:</p><pre>filterRequest = (request) =&gt; {<br>    <em>return !</em>request.url.includes(&quot;evil&quot;);<br>};</pre><pre>&lt;WebView<br>    <em>onShouldStartLoadWithRequest</em>={<em>this</em>.filterRequest}<br>/&gt;</pre><h4>Adding styling</h4><p>We might want to add some styling to make the browser experience more unique, add a loader or a custom error component, react-native-webview allows us to use two options:</p><pre>&lt;WebView<br>     {<em>/* loader */</em>}<br>     <em>renderLoading</em>={() =&gt; &lt;ActivityIndicator <em>size</em>=&quot;large&quot; <em>color</em>=&quot;#0000ff&quot; /&gt; }<br>     {<em>/* error page */</em>}<br>     <em>renderError</em>={(errorName) =&gt; &lt;Error <em>name</em>={errorName} /&gt; }<br>/&gt;</pre><h3>Wrapping up</h3><p>We are missing a few more basic features like tabs, but it’s pretty simple to do if you want to build your own browser, it’s probably easier to optimize it properly using native modules or by passing <a href="https://github.com/react-native-community/react-native-webview/blob/master/docs/Reference.md#nativeconfig">native config</a>, but for most use cases react-native-webview is a great solution.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=aea42b54740" width="1" height="1" alt=""><hr><p><a href="https://medium.com/codesight/creating-an-embedded-browser-with-react-native-aea42b54740">Creating an embedded browser with React-Native</a> was originally published in <a href="https://medium.com/codesight">codesight</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[IndexedDB]]></title>
            <link>https://medium.com/codesight/indexeddb-ea31324ff041?source=rss----37286c7be563---4</link>
            <guid isPermaLink="false">https://medium.com/p/ea31324ff041</guid>
            <category><![CDATA[indexeddb]]></category>
            <category><![CDATA[javascript]]></category>
            <dc:creator><![CDATA[Liron Navon]]></dc:creator>
            <pubDate>Thu, 24 Jan 2019 15:15:55 GMT</pubDate>
            <atom:updated>2019-01-24T15:15:58.648Z</atom:updated>
            <content:encoded><![CDATA[<p><a href="https://developer.mozilla.org/en-US/docs/Web/API/IndexedDB_API">IndexedDB</a> is a low-level browser API, designed to manage large amounts of data, it is also the only form of storage available for service workers, and is very useful for storing images, audio files and more.</p><p>IndexedDB is limited in size, but that limit depends on the browser, for storing blobs bigger than 50MB in firefox you would have to request permission, and in chrome, you get 20%</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*gP9-S54G35x9U0jkhKTMGA.jpeg" /><figcaption>An image of a library with many books 🤷‍♂️</figcaption></figure><p>We are going to create a simple todo application, we will not have to create any UI, I’m solely focusing on the javascript implementation of indexedDB, I will, however, wrap all the calls with promises that return the result and an instance of the DB for easier chaining.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/e8e1355ab8dbab6e06ceb6bcc6031050/href">https://medium.com/media/e8e1355ab8dbab6e06ceb6bcc6031050/href</a></iframe><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ea31324ff041" width="1" height="1" alt=""><hr><p><a href="https://medium.com/codesight/indexeddb-ea31324ff041">IndexedDB</a> was originally published in <a href="https://medium.com/codesight">codesight</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Javascript Notifications and Push API]]></title>
            <link>https://medium.com/codesight/javascript-notifications-and-push-api-c50909f86a5b?source=rss----37286c7be563---4</link>
            <guid isPermaLink="false">https://medium.com/p/c50909f86a5b</guid>
            <category><![CDATA[notifications]]></category>
            <category><![CDATA[web-api-development]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[web-development]]></category>
            <dc:creator><![CDATA[Liron Navon]]></dc:creator>
            <pubDate>Thu, 24 Jan 2019 15:15:29 GMT</pubDate>
            <atom:updated>2019-01-24T22:57:07.009Z</atom:updated>
            <content:encoded><![CDATA[<p>As someone who started his career as a mobile developer, one of the first and most important things I had to do, was handling push notifications — on the web, however, push notifications are much less common and the documentation can be confusing, so in this article I’m going to explain how to send a push <a href="https://developer.mozilla.org/en-US/docs/Web/API/notification">notification</a> on the web using the <a href="https://developer.mozilla.org/en-US/docs/Web/API/Push_API">push API</a>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-2ZTTSgoVBaDoT9s24Bhxg.jpeg" /><figcaption>An image of notifications on a mobile phone</figcaption></figure><h3>What are push notifications anyway? and what can we do with them?</h3><p>Let&#39;s start by separating the name into the two words that compose it:</p><p><strong>Notification</strong> — In this context, refers to native system messages that pop up on the screen outside the browser.</p><p><strong>Push</strong> — The notifications can be created by pushing data to the browser, similar to what we can achieve using <a href="https://developer.mozilla.org/en-US/docs/Web/API/WebSockets_API">WebSockets</a>, but those notifications can be pushed by the browser’s background processes, without the website or even the browser being open at the time. Well, we can do more things with push notifications, there is something that is being referred to as silent notifications/<a href="https://firebase.google.com/docs/cloud-messaging/concept-options#notifications_and_data_messages">data messages</a>, it mostly works in mobile — <a href="https://www.whatsapp.com/">WhatsApp</a>, for instance, uses them to collect your messages, those messages are saved locally to the device, that way all the messages are accessible with no web connection, and they don’t even have to be kept by WhatsApp servers, so it’s a huge plus for privacy, it’s less useful on the web, but we will see how to send data to the local storage without showing a notification.</p><h3>So, what can we do with push notifications? why should we care?</h3><p>Regular browser interactions depend on the user interacting with our service, but push notifications are our service interacting with the user, without him needing to be in our web app at the time — a good example is <a href="https://www.facebook.com/help/949954541709550">Facebook</a>, I get notifications by facebook whenever I get comments on my posts and similar events, but for each web app there are different uses for notifications, if any.</p><h3>Our first notification</h3><p>Creating a notification is pretty simple, we just need permission, and to create a notification using window.Notification() constructor, but that’s not very useful since the webpage must be open, and in that case, we can just create a regular notification with HTML5.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/ab126300b92f087da34b76e371e7b410/href">https://medium.com/media/ab126300b92f087da34b76e371e7b410/href</a></iframe><h3>Push notifications!</h3><p><a href="https://github.com/liron-navon/web-notifications-example">First of all here is the git repository</a>, you can simply clone it and run:</p><pre>npm install<br>npm start</pre><p>We are going to use inexedDB to store information from push notifications on silent mode, you can learn more about indexedDB <a href="https://medium.com/@lironnavon/indexeddb-ea31324ff041">here</a> though there are a lot of comments and it should be simple to understand, you are also expected to know express, though we will use very simple features from it.</p><p>We will also work with service workers, so we need to have HTTPS on our localhost (otherwise the browser will not allow us to access them), the simplest and quickest way to achieve this is to use <a href="https://ngrok.com/">ngrok</a> it’s a free open source solution to create a proxy from their servers to our local host, we can use it like this:</p><pre>npm install -g ngrok<br>ngrok http &lt;PORT_NUMBER&gt;</pre><pre># we will get the following result for port 3000 #<br>Session Status                online<br>Session Expires               7 hours, 59 minutes<br>Version                       2.2.8<br>Region                        United States (us)<br>Web Interface                 <a href="http://127.0.0.1:4040/">http://127.0.0.1:4040</a><br>Forwarding                    <a href="http://ef169615.ngrok.io/">http://ef169615.ngrok.io</a> -&gt; localhost:3000<br>Forwarding                    <a href="https://ef169615.ngrok.io/">https://ef169615.ngrok.io</a> -&gt; localhost:3000</pre><p>What we want is the second &quot;Forwarding&quot;, the one with the https, this will redirect from this URL &quot;<a href="http://ef169615.ngrok.io/">http://ef169615.ngrok.io</a>&quot; to localhost on port 3000.</p><p>I will only show here snippets from the code, so you should follow with the <a href="https://github.com/liron-navon/web-notifications-example">Github repository</a>. Let’s start by looking at the project structure:</p><p>-<strong>package.json: </strong>we will only use express, body-parser, and web-push.<br>-<strong>server.js: </strong>this is our server, it will serve the files from the public directory and manage the notifications API.<br>-<strong>Public/</strong><br> — <strong>index.html</strong><br> —<strong> indexed-db.js: </strong>a script to update the UI with data from the indexedDB.<br> — <strong>register-push.js:</strong> a script to register our service worker<br> — <strong>service-worker.js:</strong> the service worker will be the one listening to the push notifications.<strong><br> — lazy-engineering-logo.png: </strong>just a default icon for the notifications 😅.</p><h3>server.js:</h3><p>The first function we will look at is the one where we generate the keys, those keys will be used like so: <br>publicKey: will be sent to the client to create a push context by the browser.<br>privateKey: will be used when we send the notification the browser push service, the service is different in chrome, or firefox, or opera, etc…<br>We should store the keys to keep identifying the client, so if none exist, we generate new keys using webPush and store them in a config file, just make sure you don’t lose those or the push servers will lose the clients.</p><pre>function getVAPIDKeys() {<br>  <em>// check if we saved the config already<br>  </em>if(fs.existsSync(localConfigFile)) {<br>    return JSON.parse(fs.readFileSync(localConfigFile, ‘utf8’));<br>  }</pre><pre><em>  // we will create new config by generating new keys<br>  </em>const generatedKeys = webPush.generateVAPIDKeys();<br>  fs.writeFileSync(localConfigFile, JSON.stringify(generatedKeys));<br>  console.log(`new VAPID keys were generated and saved to ${localConfigFile}`);<br>  return generatedKeys;<br>  }</pre><p>We use initiate webPush with the keys, serve the public key through ‘/api/vapid-public-key’ so the client will have access to it.<br>And for the ‘/api/send-notification’ route we simply need to call:</p><pre>webPush.sendNotification(subscription, JSON.stringify(payload), options)</pre><p>We can send whatever we want in the payload, but it should be a string, so if we want to send to the client different icons, title, body text and options, we should stringify the request and parse it on the client.<br>And that’s mostly it for the server, the rest is simple <a href="https://expressjs.com/">express</a> code.</p><h3><strong>register-push.js</strong></h3><p>We need to create a service-worker, register it through the browser’s push manager. When we subscribe we have to use “userVisibleOnly” as true, otherwise, <a href="https://developers.google.com/web/fundamentals/push-notifications/subscribing-a-user">chrome will throw an error</a> (but we don’t really have to show a notification 🙆‍♀️).</p><pre><em>// we register the service worker script<br></em>navigator.serviceWorker.register(“service-worker.js”);<br>const registration = await navigator.serviceWorker.ready;<br>let subscription = await registration.pushManager.getSubscription();</pre><pre><em>// we will create a new subscripion if one doesn’t exist, or it has expired<br></em>if (!subscription) {<br>  <em>// we need the public key from the server</em><br>  const response = await fetch(`/api/vapid-public-key`);<br>  const vapidPublicKey = await response.text();<br>  subscription = await registration.pushManager.subscribe({<br>    userVisibleOnly: true,<br>    applicationServerKey: urlBase64ToUint8Array(vapidPublicKey)<br>   });<br>}</pre><p>The next part is sending the notification, it’s a simple fetch request, the request would look something like this for chrome, but it’s different for each browser, the payload can be whatever we want, with restrictions about the size, the delay is an option to send to our server for experimentation, and the ttl will be sent to the push server (in this case <a href="https://fcm.googleapis.com/fcm/send/fBHenUIrqWk:APA91bHuIyHQpBOrHNZQkJGkUSe2z0QdmZDykcEr9b0KLS_GDwKIFjbY2cBU9lDlAQoQ9yovenBbhTFVoPyz6O8V5C_Rcqxh0t7QhdtLfA11cVgeBuXvTkQWQB-pGWkZmnTCruLst2Am">fcm.googleapis.com</a>) to tell them how long we want them to hold onto the message in seconds, the default is 4 weeks, and that’s this magic number, in seconds.</p><pre>{<br>  “subscription”:{<br>    “endpoint”:”<a href="https://fcm.googleapis.com/fcm/send/fBHenUIrqWk:APA91bHuIyHQpBOrHNZQkJGkUSe2z0QdmZDykcEr9b0KLS_GDwKIFjbY2cBU9lDlAQoQ9yovenBbhTFVoPyz6O8V5C_Rcqxh0t7QhdtLfA11cVgeBuXvTkQWQB-pGWkZmnTCruLst2Am">https://fcm.googleapis.com/fcm/send/</a>...&quot;,<br>    &quot;expirationTime&quot;:null,<br>    &quot;keys&quot;:{<br>      &quot;p256dh&quot;:&quot;...&quot;,<br>      &quot;auth&quot;:&quot;...&quot;<br>    }<br>  },<br>  &quot;payload&quot;:{<br>    &quot;title&quot;:&quot;My title”,<br>    ”body”:”My body”,<br>    ”icon”:”/my-icon.png”,<br>    ”silent”:true<br>  },<br>  ”delay”:”0&quot;,<br>  ”ttl”:”2419200&quot;<br>}</pre><p>After the service-worker will be registered, we need to save the “subscription” parameter in a database, then we can make push requests whenever we need.</p><h3><strong>service-worker.js</strong></h3><p>That’s the actually interesting part in our little app, it will parse the payload, and according to the ”silent” parameter we are sending, we will decide if to show a notification or simply store the notification locally, since we have no window in service worker, we cannot store it in local storage, that’s why we are going to store it in indexedDB.<br>The <a href="https://developer.mozilla.org/en-US/docs/Web/API/ExtendableEvent/waitUntil">“event.waitUntil”</a> will tell the browser to give us time until our promise is resolved, so the process will not exit before we are done.</p><pre>self.addEventListener(“push”, event =&gt; {<br>  console.log(“We got a push notification”);<br>  const payload = event.data ? event.data.text() : ‘{}’;<br>  const {<br>    title = “no title”,<br>    body = “no body”,<br>    icon = “/lazy-engineering-logo.png”,<br>    silent = false<br>  } = JSON.parse(payload);</pre><pre>  if (silent) {<br>    <em>// will wait until the promise is resolved<br>    </em>return event.waitUntil(<br>      openIndexDB(self.indexedDB)<br>      .then((db) =&gt; addPush(db, `${title} — ${body}`))<br>      .then(() =&gt; console.log(‘inserted to indexedDB’))<br>    )<br>  }</pre><pre><em>  // will wait until the promise is resolved<br>  </em>event.waitUntil(<br>    self.registration.showNotification(title, {<br>    body,<br>    icon,<br>    <em>// we can also add vibrations for mobile devices<br>    </em>vibrate: [200, 100, 200, 100, 200, 100, 200]<br>    })<br>  );<br>});</pre><p>About <a href="https://developer.mozilla.org/en-US/docs/Web/API/Vibration_API#Vibration_patterns">vibration</a>, it is an array of numbers, that define milliseconds, it is read like this: for [100, 200, 300], we vibrate 100ms, rest 200ms, and vibrate 300ms again.<br>There are much more options for the <a href="https://developer.mozilla.org/en-US/docs/Web/API/Notification/Notification">notification constructor</a>, such as actions, and requires interaction, there are a lot of ways to make interaction with notifications!</p><p>The last file we are not going to go through here, is <strong>indexed-db.js, </strong>but it is simple, it just creates an interval, reads from the indexDB, and display it.</p><h3>Summary</h3><p>The web notification standards are still evolving, and so does the push standards, we can use the notifications API for a lot of nice interactions on the web, and for better support of offline first web apps!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c50909f86a5b" width="1" height="1" alt=""><hr><p><a href="https://medium.com/codesight/javascript-notifications-and-push-api-c50909f86a5b">Javascript Notifications and Push API</a> was originally published in <a href="https://medium.com/codesight">codesight</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Node worker threads]]></title>
            <link>https://medium.com/codesight/node-worker-threads-b57a32d84845?source=rss----37286c7be563---4</link>
            <guid isPermaLink="false">https://medium.com/p/b57a32d84845</guid>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[thread-workers]]></category>
            <category><![CDATA[node-js-tutorial]]></category>
            <category><![CDATA[nodejs]]></category>
            <dc:creator><![CDATA[Liron Navon]]></dc:creator>
            <pubDate>Tue, 22 Jan 2019 08:43:15 GMT</pubDate>
            <atom:updated>2020-11-09T18:50:38.703Z</atom:updated>
            <content:encoded><![CDATA[<p><a href="https://nodejs.org/api/worker_threads.html">Worker threads</a> are already available from version 10.5, but now at newer versions, the feature flag is removed and we can start using them.</p><h3>What are worker threads?</h3><p>The main reason against node is that it is <a href="https://www.altexsoft.com/blog/engineering/the-good-and-the-bad-of-node-js-web-app-development/">single threaded</a> and therefore cannot make use of all the machine resources, but with worker threads, we can create multiple threads to delegate work from the main thread and keep it free to process new requests faster.</p><p>Node is known as an asynchronous programming runtime for javascript, in node we work in a <strong>concurrent</strong> way (with promises and callbacks), but here we will understand how to work in a <strong>parallel</strong> way, and why and when we should even do it, you can read more about the difference between concurrency and parallelism <a href="https://howtodoinjava.com/java/multi-threading/concurrency-vs-parallelism/">here</a>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_NsyZY8sxJC1AA6tWYB3KQ.jpeg" /></figure><h3>When to use worker threads?</h3><p>As the documentation states:</p><blockquote>Workers (threads) are useful for performing CPU-intensive JavaScript operations. They will not help much with I/O-intensive work. Node.js’s built-in asynchronous I/O operations are more efficient than Workers can be.</blockquote><h3>Let&#39;s get started!</h3><p>For working with worker threads lets first make sure we have node version of 11.7.0 or higher (with the command “node -v”), you can update it with <a href="https://github.com/creationix/nvm">nvm</a>.</p><p>We are going to do a time consuming heavy CPU operation — sorting a very large array, millions of elements. The worker_threads API exports a few variables and functions, here is a shot, simple description for each:</p><p><strong>Worker (function)</strong>: A class to create a new worker thread, it accepts a path to a script, and options object that includes a “workerData” variable, it should be called to spawn a new thread.</p><p><strong>workerData (object)</strong>: This variable will contain the data that is passed to the worker thread through the constructor of “Worker”, we can use the instance to emit messages into the worker, or listen to events from it, kill and restart it.</p><p><strong>isMainThread (boolean)</strong>: A variable that tells us if we are on the main thread, you can use it to make decisions from the workers (remember that a worker thread can spawn another worker thread, which means both will not be in the main thread.)</p><p><strong>parentPort (object)</strong>: The child thread can use this object to emit messages to the parent thread.</p><p>Ok, now that we know what API the worker threads have, we can see an example, the example is well documented.</p><p>index.js is in our main thread.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c76ea930b3514748141a725f8cbf8563/href">https://medium.com/media/c76ea930b3514748141a725f8cbf8563/href</a></iframe><p>sorter.js is a script made to work with the worker_threads API as a worker.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/a89bb1dd87779b7c4fd52101c929a76e/href">https://medium.com/media/a89bb1dd87779b7c4fd52101c929a76e/href</a></iframe><p>You can run it with: node index.js , our worker can now sort a simple array, but in order to see the difference, we need to scale this operation across multiple workers.</p><h3>Let’s see the difference</h3><p>That’s nice, but unfortunately, threads in node.js are pretty heavy, each of them is an independent node instance with extra startup steps, so using 1 worker is usually pretty useless, but we can improve the way we use the workers by distributing the load over multiple workers. We are going to do an operation that may take a minute or two in large numbers, so let’s install <a href="https://github.com/sindresorhus/ora">ora</a> to show a nice loader in the terminal, this is our only dependency.</p><pre>npm init<br>npm install ora --save</pre><p>Here is a way to compare the speed of sorting millions of random numbers (change the elements variable to the wanted number, 5million is a nice start) with one worker, 8(I have 8 CPU&#39;s on my mac) workers, and with no worker at all.<br>I had to increase the memory limit in order to handle so many floating points numbers (it started to crush above 10 million elements), you can increase the memory by applying the flag --max-old-space-size and specifying the size in megabytes (8gb in this case).</p><pre>node --max-old-space-size=8192 index.js</pre><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/1e52c13f021f8894a6bed96ebece2777/href">https://medium.com/media/1e52c13f021f8894a6bed96ebece2777/href</a></iframe><p>This is the output I got:</p><pre># for 5 million items:<br>sorted 5000000 items, with 1 worker in 11296ms (11.2 seconds)<br>sorted 5000000 items, without workers in 7045ms (7 seconds)<br>sorted 5000000 items, with 8 workers in 2049ms (2 seconds)</pre><pre># for 20 million items<br>sorted 20000000 items, with 1 worker in 63597ms (63.5 seconds)<br>sorted 20000000 items, without workers in 48189ms (48 seconds)<br>sorted 20000000 items, with 8 workers in 8747ms (8.7 seconds)</pre><p>Well, this is a big difference, please notice that when passing information to the threads and back we have a large overhead of serializing and deserializing the data — which causes a large overhead to performance.<br>They don&#39;t block the main thread, of course, Promises can work just as well at keeping the main thread responsive, but a lot of promises running at the same time on the same thread may cause it to be slow and unresponsive, and distributing the load over a bunch of workers can save us a lot of precious time.</p><p>When working in a real-world scenario you should manage your own pool of workers and manage them so the number of running threads will not exceed the number of CPU’s, we can achieve this with <a href="https://github.com/watson/worker-threads-pool">worker-thread-pool</a>, we only need to change out “sortArrayWithWorker” function, and initiate the thread pool like so:</p><pre>const Pool = require(&quot;worker-threads-pool&quot;);<br>const pool = new Pool({ max: cpuCount });</pre><pre>const sortArrayWithWorker = arr =&gt; {<br>return new Promise((resolve, reject) =&gt; {<br>  pool.acquire(workerScript, { workerData: arr }, (err, worker) =&gt; {<br>    if (err) {<br>      return reject(err);<br>    }<br>    worker.once(&quot;message&quot;, resolve);<br>    worker.once(&quot;error&quot;, reject);<br>    });<br>  });<br>};</pre><p>Now we can safely use more processors than there are available without fearing running out of processors (the pool will manage them for us and keep a steady number of threads running).</p><pre>const result = await distributeLoadAcrossWorkers(100);</pre><p>Running the threads like so will actually make them slower, before, running the 5milion example with 8 real threads took 2049 milliseconds, now with “100” threads took me 4302 milliseconds — still much faster than running it with no worker threads at all, as we increase the number, the process will be slower since the pool will have to handle more instances.</p><h3>Conclusion</h3><p>Worker threads are great! unfortunately, they are still very heavy and should be used with care, don’t just throw them around as a way to optimize stuff, they can be used to increase the speed of an HTML parser, for instance, or can to increase the speed of bundling.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b57a32d84845" width="1" height="1" alt=""><hr><p><a href="https://medium.com/codesight/node-worker-threads-b57a32d84845">Node worker threads</a> was originally published in <a href="https://medium.com/codesight">codesight</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>