Building a WebRTC Video Chat Application with PeerJS and Node.js

This is image title
The WebRTC brings many benefits to the user and the developer that have been less available in the past to create communication and collaboration tools on the web. For example it offers a variety of ways to connect, with the common element of a live chats and videos. To create a real-time voice or video connections, PeerJS is one of the most awesome libraries that allows you to implement such a feature in your web application without having (too much) headaches. PeerJS wraps the browser’s WebRTC implementation to provide a complete, configurable, and easy-to-use peer-to-peer connection API. Equipped with nothing but an ID, a peer can create a P2P data or media stream connection to a remote peer easily.

Before continue

You will need to be patient as at first try it may not work as expected if you don’t configure everything correctly. So be persistent, read carefully all the instructions and you may succeed ad first time.

Content guide

This tutorial will be extense, so here as a quick introduction to all the steps that you will need to follow:

  1. Get some Auto-signed SSL certificate for testing.
  2. Create Demo Project Structure
  3. Create a secure local server with Express to serve our HTML,CSS and JS files.
  4. Create a secure PeerJS server that handles the exchange of information.
  5. Write Code to handle Videochat.
  • Understand how PeerJS works.
  • Create markup to create an example chat.
  1. Allow inbound connections for Node.js and update client host (only if local testing)
  2. Run Servers and Test

1. Create or get some SSL Certificate

In order to work either in production or locally to test, you will need to handle your project using a SSL certificate, otherwise some things on the browser may fail due to user permissions. This step is totally up to you, so according to your operative system you may search for another tutorial about how to create your own self signed SSL certificates. This article shows how to create a self signed certificate using openssl in Windows.

Alternatively, you can download self-signed certificates from the example repository in Github here and use them in your own implementation.

2. Demo Project Structure

To create a basic videochat, we’ll need a basic structure of a HTML project and JavaScript:

Note
All the files (except the certificates and peer.min.js) should be empty as we’ll tell you what to write inside every file later.

YourProjectFolder
├───certificates
    ├── cert.pem
    └── key.pem
├───public
    ├── index.html
    ├── website-server.js
    ├── source
    │   └── js
    |       ├── peer.min.js
    │       └── scripts.js
    └── package.json
├───server
    ├── peer-server.js
    └── package.json

You will need 3 folders inside the test folder, namely certificates, public and server. On the certificates file you will need to store the required files to make the server works in HTTPS (see step 1). On the public folder you will find the index file that allows the user to chat and execute a videocall with someone else, besides the scripts inside source are the source code of peer.js for the client side and the scripts.js that will be written on the step 5.

Remember that the structure doesn’t need to be the same, it is just an example, however the paths of the files in the code will follow this pattern, so if you change the structure, be aware to change it in your code too.

3. Setup Test Local Server

For our example, we’ll make accesible a simple html file (index.html) at https://localhost:8443 . To create our server, we’ll use the express module, so open a terminal, switch to the project/public directory and modify the package.json file at least with the following data, note that you can change the name of your project at the version, the main point is that you need to create a valid file:

{
    "name": "peerjs-videochat-application-client",
    "version": "1.0.0"
}

Once thepackage.jsonfile is valid, proceed to install the Express module executing:

npm install express

After the installation of this module, you will be able to setup a local server easily. Now go to the public folder of the project and modify the website-server.js file with the following code:

Note : The servers uses the certificate files mentioned on the first step, so if you decided to change the structure of your example project, be sure to change the path to the certificate files too.

// project/public/website-server.js
/**
 * This script starts a https server accessible at https://localhost:8443
 * to test the chat
 *
 * @author Carlos Delgado (Our Code World)
 */
var fs     = require('fs');
var http   = require('http');
var https  = require('https');
var path   = require("path");
var os     = require('os');
var ifaces = os.networkInterfaces();

// Public Self-Signed Certificates for HTTPS connection
var privateKey  = fs.readFileSync('./../certificates/key.pem', 'utf8');
var certificate = fs.readFileSync('./../certificates/cert.pem', 'utf8');

var credentials = {key: privateKey, cert: certificate};
var express = require('express');
var app = express();

var httpServer = http.createServer(app);
var httpsServer = https.createServer(credentials, app);

/**
 *  Show in the console the URL access for other devices in the network
 */
Object.keys(ifaces).forEach(function (ifname) {
    var alias = 0;

    ifaces[ifname].forEach(function (iface) {
        if ('IPv4' !== iface.family || iface.internal !== false) {
            // skip over internal (i.e. 127.0.0.1) and non-ipv4 addresses
            return;
        }
        
        console.log("");
        console.log("Welcome to the Chat Sandbox");
        console.log("");
        console.log("Test the chat interface from this device at : ", "https://localhost:8443");
        console.log("");
        console.log("And access the chat sandbox from another device through LAN using any of the IPS:");
        console.log("Important: Node.js needs to accept inbound connections through the Host Firewall");
        console.log("");

        if (alias >= 1) {
            console.log("Multiple ipv4 addreses were found ... ");
            // this single interface has multiple ipv4 addresses
            console.log(ifname + ':' + alias, "https://"+ iface.address + ":8443");
        } else {
            // this interface has only one ipv4 adress
            console.log(ifname, "https://"+ iface.address + ":8443");
        }

        ++alias;
    });
});

// Allow access from all the devices of the network (as long as connections are allowed by the firewall)
var LANAccess = "0.0.0.0";
// For http
httpServer.listen(8080, LANAccess);
// For https
httpsServer.listen(8443, LANAccess);

// Serve the index.html file as content of the / route
app.get('/', function (req, res) {
    res.sendFile(path.join(__dirname+'/index.html'));
});

// Expose the js resources as "resources"
app.use('/resources', express.static('./source'));

This code setups a very basic Express server that as mentioned can be accessed at localhost in the port 8443 (https) in the browser when executed. Besides it will list (once executed in the console) the address where it can be accessed from another devices within the LAN (refer to step 6), alternatively you can remove it if you are deploying it on the production server.

Save the changes on the file and go to the next step.

4. Setup PeerJS Server

PeerServer helps broker connections between PeerJS clients and the data is not proxied through the server. To install the server side module of PeerJS, open the package.json file created at project/server and add at least the required parameters to create a valid file:

{
    "name": "peerjs-videochat-application-server",
    "version": "1.0.0"
}

Once created, in the same directory run the following command to install the server

npm install peer

Proceed to modify the peer-server.js file inside the server folder (project/server) of your project with the following content:

// project/server/peer-server.js
var fs = require('fs');
var PeerServer = require('peer').PeerServer;

var server = PeerServer({
    port: 9000,
    path: '/peerjs',
    ssl: {
        key: fs.readFileSync('./../certificates/key.pem', 'utf8'),
        cert: fs.readFileSync('./../certificates/cert.pem', 'utf8')
    }
});

As you can see, the configuration of the server side for PeerJS is very simple and you won’t need to do anything else in the server side. You can add some events listeners, however it isn’t required as Peer Server will handle all the required logic automatically. This server will run on your server at the port 9000 when executed.

This is image title

5. Setup Client Side Code

The client side can be very simple. Imagine this as another boring web page but that does something awesome. The styles that you provide to your project is up to you, for example we are using the bootstrap framework to create a nice layout using the Cerulean Theme from Bootswatch.

The Markup (project/public/index.html) that we’ll use for our example looks like:

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <title>Video Chat with PeerJS</title>
    
    <!-- Using some styles Bootswatch CSS from cdn -->
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootswatch/3.3.7/cerulean/bootstrap.min.css">
</head>

<body>
    <div class="container">
        <div class="row">
            <div class="col-md-6 col-lg-6">
                <!-- 
                    Display video of the current user
                    Note: mute your own video, otherwise you'll hear yourself ...
                 -->
                <div class="text-center">
                    <video id="my-camera"  width="300" height="300" autoplay="autoplay" muted="true" class="mx-auto d-block"></video>
                    <span class="label label-info">You</span>
                </div>
            </div>

            <div class="col-md-6 col-lg-6">
                <!-- Display video of the connected peer -->
                <div class="text-center">
                    <video id="peer-camera" width="300" height="300" autoplay="autoplay" class="mx-auto d-block"></video>
                    <span class="label label-info" id="connected_peer"></span>
                </div>
            </div>
        </div>

        <div class="row">
            <h1 class="text-center">
                Videochat Example
                <br>
                <small> Share the following ID with the pal that wants to talk with you</small>
            </h1>
            <!-- The ID of your current session -->
            <h4 class="text-center">
                <span id="peer-id-label"></span>
            </h4>
            <div class="col-md-12 col-lg-12">
                <div class="form-horizontal" id="connection-form">
                    <fieldset>
                        <legend>Connection Form</legend>
                        <div class="form-group">
                            <label for="name" class="col-lg-2 control-label">Username</label>
                            <div class="col-lg-10">
                                <input type="text" class="form-control" name="name" id="name" placeholder="Your random username">
                            </div>
                        </div>
                        <div class="form-group">
                            <label for="peer_id" class="col-lg-2 control-label">Peer ID (id of your pal)</label>
                            <div class="col-lg-10">
                                <input type="text" class="form-control" name="peer_id" id="peer_id" placeholder="Peer ID" autocomplete="off" autocorrect="off" autocapitalize="off" spellcheck="false">
                                
                                <!-- Show message if someone connected to the client -->
                                <div id="connected_peer_container" class="hidden">
                                    An user is already connected to your session. Just provide a name to connect !
                                </div>
                            </div>
                        </div>
                        <div class="form-group">
                            <div class="col-lg-10 col-lg-offset-2">
                                <button id="connect-to-peer-btn" class="btn btn-primary">Connect to Peer</button>
                            </div>
                        </div>
                    </fieldset>
                </div>
            </div>
            <div class="col-md-12 col-lg-12">
                <div id="chat" class="hidden">
                    <div id="messages-container">
                        <div class="list-group" id="messages"></div>
                    </div>
                    <div id="message-container">
                        <div class="form-group">
                            <label class="control-label">Live chat</label>
                            <div class="input-group">
                                <span class="input-group-btn">
                                    <button id="call" class="btn btn-info">Call</button>
                                </span>
                                <input type="text" class="form-control" name="message" id="message" placeholder="Your messag here ...">
                                <span class="input-group-btn">
                                    <button id="send-message" class="btn btn-success">Send Message</button>
                                </span>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>
    
    <!-- 
        Include the Client Side version of peer.js 
        using a script tag !
    -->
    <script src="resources/js/peer.min.js"></script>

    <!-- Include the scripts that will handle the chat -->
    <script src="resources/js/script.js"></script>
</body>

</html>

The important on the structure of the markup, is that you follow the providen IDs to make for the following JavaScript. Note that the first video tag (the one that will display your own video) needs to have the muted attribute set to true, otherwise you will hear yourself once the transmission begins. The Client version of Peer.js needs to be included as well, this file can be obtained from the official repository here, or from any free CDN. The point is that the peer.min.js file needs to be located in project/public/js.

Now for the project/public/js/scripts.js file, we’ll write the code that handles so start by writing a DOMContentLoaded event listener:

// When the DOM is ready
document.addEventListener("DOMContentLoaded", function(event) {
    // All the code of scripts.js here ...
}, false);

All the code that we’ll explain now, we’ll need to be inside of the previous callback. The first you need to do, is to decide how will be the initialization on the client side of PeerJS and create some global variables (only for the scripts.js file):

var peer_id;
var username;
var conn;

/**
 * Important: the host needs to be changed according to your requirements.
 * e.g if you want to access the Peer server from another device, the
 * host would be the IP of your host namely 192.xxx.xxx.xx instead
 * of localhost.
 * 
 * The iceServers on this example are public and can be used for your project.
 */
var peer = new Peer({
    host: "localhost",
    port: 9000,
    path: '/peerjs',
    debug: 3,
    config: {
        'iceServers': [
            { url: 'stun:stun1.l.google.com:19302' },
            {
                url: 'turn:numb.viagenie.ca',
                credential: 'muazkh',
                username: 'webrtc@live.com'
            }
        ]
    }
});

In this step plays the WebRTC knowledge an important role, so if you don’t know nothing about it, we recommend you to read more about the ice Servers in this well written article of HTML5 Rocks here. This example uses free Ice Servers to make it work, however they may not run or be active forever, so it’s recommendable in case you are running a business, to buy and own your own STUN or TURN servers. So you will have all of the infrastructure you need to deploy production grade WebRTC applications.

By the otherside, we are using localhost as the host that usually maybe enough for production to make it work. In case you are testing, you know that you can’t use the same computer to test the videochat because 2 browsers can’t have access to the camera at the same time, so you probably will expose the Local Server to the LAN (explanation in the next step) by changing the host to the IP of your computer.

Now, add some event listeners to the peer that will allow you to execute some actions when the most important events of Peer happen as the video call etc:

// Once the initialization succeeds:
// Show the ID that allows other user to connect to your session.
peer.on('open', function () {
    document.getElementById("peer-id-label").innerHTML = peer.id;
});

// When someone connects to your session:
// 
// 1. Hide the peer_id field of the connection form and set automatically its value
// as the peer of the user that requested the connection.
// 2. Update global variables with received values
peer.on('connection', function (connection) {
    conn = connection;
    peer_id = connection.peer;

    // Use the handleMessage to callback when a message comes in
    conn.on('data', handleMessage);

    // Hide peer_id field and set the incoming peer id as value
    document.getElementById("peer_id").className += " hidden";
    document.getElementById("peer_id").value = peer_id;
    document.getElementById("connected_peer").innerHTML = connection.metadata.username;
});

peer.on('error', function(err){
    alert("An error ocurred with peer: " + err);
    console.error(err);
});

/**
 * Handle the on receive call event
 */
peer.on('call', function (call) {
    var acceptsCall = confirm("Videocall incoming, do you want to accept it ?");

    if(acceptsCall){
        // Answer the call with your own video/audio stream
        call.answer(window.localStream);

        // Receive data
        call.on('stream', function (stream) {
            // Store a global reference of the other user stream
            window.peer_stream = stream;
            // Display the stream of the other user in the peer-camera video element !
            onReceiveStream(stream, 'peer-camera');
        });

        // Handle when the call finishes
        call.on('close', function(){
            alert("The videocall has finished");
        });

        // use call.close() to finish a call
    }else{
        console.log("Call denied !");
    }
});

Now add some helper methods to display the received and sent data in the listview and to request the video/audio on the browser:

/**
 * Starts the request of the camera and microphone
 * 
 * @param {Object} callbacks 
 */
function requestLocalVideo(callbacks) {
    // Monkeypatch for crossbrowser geusermedia
    navigator.getUserMedia = navigator.getUserMedia || navigator.webkitGetUserMedia || navigator.mozGetUserMedia;

    // Request audio an video
    navigator.getUserMedia({ audio: true, video: true }, callbacks.success , callbacks.error);
}

/**
 * Handle the providen stream (video and audio) to the desired video element
 * 
 * @param {*} stream 
 * @param {*} element_id 
 */
function onReceiveStream(stream, element_id) {
    // Retrieve the video element according to the desired
    var video = document.getElementById(element_id);
    // Set the given stream as the video source 
    video.src = window.URL.createObjectURL(stream);

    // Store a global reference of the stream
    window.peer_stream = stream;
}

/**
 * Appends the received and sent message to the listview
 * 
 * @param {Object} data 
 */
function handleMessage(data) {
    var orientation = "text-left";

    // If the message is yours, set text to right !
    if(data.from == username){
        orientation = "text-right"
    }

    var messageHTML =  '<a href="javascript:void(0);" class="list-group-item' + orientation + '">';
            messageHTML += '<h4 class="list-group-item-heading">'+ data.from +'</h4>';
            messageHTML += '<p class="list-group-item-text">'+ data.text +'</p>';
        messageHTML += '</a>';

    document.getElementById("messages").innerHTML += messageHTML;
}

As next, define the event listeners that react to every action from the user interface as the login event, start call etc:

/**
 * Handle the send message button
 */
document.getElementById("send-message").addEventListener("click", function(){
    // Get the text to send
    var text = document.getElementById("message").value;

    // Prepare the data to send
    var data = {
        from: username, 
        text: text 
    };

    // Send the message with Peer
    conn.send(data);

    // Handle the message on the UI
    handleMessage(data);

    document.getElementById("message").value = "";
}, false);

/**
 *  Request a videocall the other user
 */
document.getElementById("call").addEventListener("click", function(){
    console.log('Calling to ' + peer_id);
    console.log(peer);

    var call = peer.call(peer_id, window.localStream);

    call.on('stream', function (stream) {
        window.peer_stream = stream;

        onReceiveStream(stream, 'peer-camera');
    });
}, false);

/**
 * On click the connect button, initialize connection with peer
 */
document.getElementById("connect-to-peer-btn").addEventListener("click", function(){
    username = document.getElementById("name").value;
    peer_id = document.getElementById("peer_id").value;
    
    if (peer_id) {
        conn = peer.connect(peer_id, {
            metadata: {
                'username': username
            }
        });
        
        conn.on('data', handleMessage);
    }else{
        alert("You need to provide a peer to connect with !");
        return false;
    }

    document.getElementById("chat").className = "";
    document.getElementById("connection-form").className += " hidden";
}, false);

As final step (and it’s execution is not immediately required) you can call the requestLocalVideo method to start your own stream (that will be used to send to the other user):

/**
 * Initialize application by requesting your own video to test !
 */
requestLocalVideo({
    success: function(stream){
        window.localStream = stream;
        onReceiveStream(stream, 'my-camera');
    },
    error: function(err){
        alert("Cannot get access to your camera and video !");
        console.error(err);
    }
});

This is image title

6. Allow inbounds connection for Node.js (only if working locally)

If you try to access the mentioned address (localhost:8443) but with the IP of your computer instead of localhost from your mobile devices (an Android Device) or other device on your local area network to make the videochat test (because you can’t test the videochat on the same computer) and Node.js is blocked by some rule of the Firewall, it won’t (probably) simply work :

This is image title

If you’re sure that the server is running on your computer, then the problem could be caused by a Firewall restriction and to make it work you will need to allow all inbound connections to the Node.js application in your computer. For example, in Windows you could simply open the Firewall, navigate to the Inbound Rules and search Node.js in the list:

This is image title

Right click on the selected item of Node.js and select Properties from the context menu. In this menu, navigate to the General tab and in the Action area, select the Allow the connection radio button:

This is image title

That should immediately work, however to be sure, restart the terminal in which Node was open and start it again.

7. Running the Chat

If everything went as expected, you could be able now to test the videochat by yourself. All that you need to do is to run the server file of every directory (public and server) with Node and let them running in the background.

Open a new terminal and switch to the project/public directory and run the following command:

node website-server.js

This will start the server for your website to test the videochat. Then open another terminal, switch to the project/server directory and run the following command:

node peer-server.js

This one will start the Chat server with Peer. Let the 2 terminal active and access the https://localhost:8443 url with your browser and you will see the Videochat template. For this example, we’ll use 2 users namely Mr. Huskee (the first user) and Mr. Doge (the second user):
This is image title

In this case the camera of Mr. Huskee starts automatically as defined behaviour that can be obviously changed as you want. The interface at this point expects for someone to connect using the ID at the middle of the screen, that means that if you want to start a videochat with someone, you only need to provide the ID to the other user. If you are not waiting for someone to connect, but you want to connect with someone, then you need the ID of the other user. With the other computer, or a mobile device in this example, Mr. Doge wants to start a chat with Mr. Huskee, so we need to type the ID of Mr. Huskee (in this case 8n9hrtc80tzhvlb6) in our form and our name:

This is image title

Once Mr. Doge has the basic data of the form and clicks on Connect to Peer, the screen of Mr. Huskee will be automatically updated and will show the message that someone is connected to the session namely Mr. Doge and he only needs to provide its username:

This is image title

Now Mr. Huskee is logged in and can chat with Mr. Doge easily, therefore he can’t provide the Peer ID to connect to someone else because he already has a connection. The chat at this moment doesn’t have videochat but only text chat:

This is image title

Therefore someone would need to click on the Call button, that in this case will be Mr. Doge at the mobile device. Then Mr. Huskee will receive the prompt in the browser if he want’s to start the call:

This is image title

If accepted, the Video Chat will start without a problem and they can talk and write in the same way they do with applications like Skype:

This is image title

As mentioned at the beginning of the article, you can find the source code of this example in the official repository at Github here.

Happy coding !

This is image title

#node-js #javascript

What is GEEK

Buddha Community

Building a WebRTC Video Chat Application with  PeerJS and Node.js

NBB: Ad-hoc CLJS Scripting on Node.js

Nbb

Not babashka. Node.js babashka!?

Ad-hoc CLJS scripting on Node.js.

Status

Experimental. Please report issues here.

Goals and features

Nbb's main goal is to make it easy to get started with ad hoc CLJS scripting on Node.js.

Additional goals and features are:

  • Fast startup without relying on a custom version of Node.js.
  • Small artifact (current size is around 1.2MB).
  • First class macros.
  • Support building small TUI apps using Reagent.
  • Complement babashka with libraries from the Node.js ecosystem.

Requirements

Nbb requires Node.js v12 or newer.

How does this tool work?

CLJS code is evaluated through SCI, the same interpreter that powers babashka. Because SCI works with advanced compilation, the bundle size, especially when combined with other dependencies, is smaller than what you get with self-hosted CLJS. That makes startup faster. The trade-off is that execution is less performant and that only a subset of CLJS is available (e.g. no deftype, yet).

Usage

Install nbb from NPM:

$ npm install nbb -g

Omit -g for a local install.

Try out an expression:

$ nbb -e '(+ 1 2 3)'
6

And then install some other NPM libraries to use in the script. E.g.:

$ npm install csv-parse shelljs zx

Create a script which uses the NPM libraries:

(ns script
  (:require ["csv-parse/lib/sync$default" :as csv-parse]
            ["fs" :as fs]
            ["path" :as path]
            ["shelljs$default" :as sh]
            ["term-size$default" :as term-size]
            ["zx$default" :as zx]
            ["zx$fs" :as zxfs]
            [nbb.core :refer [*file*]]))

(prn (path/resolve "."))

(prn (term-size))

(println (count (str (fs/readFileSync *file*))))

(prn (sh/ls "."))

(prn (csv-parse "foo,bar"))

(prn (zxfs/existsSync *file*))

(zx/$ #js ["ls"])

Call the script:

$ nbb script.cljs
"/private/tmp/test-script"
#js {:columns 216, :rows 47}
510
#js ["node_modules" "package-lock.json" "package.json" "script.cljs"]
#js [#js ["foo" "bar"]]
true
$ ls
node_modules
package-lock.json
package.json
script.cljs

Macros

Nbb has first class support for macros: you can define them right inside your .cljs file, like you are used to from JVM Clojure. Consider the plet macro to make working with promises more palatable:

(defmacro plet
  [bindings & body]
  (let [binding-pairs (reverse (partition 2 bindings))
        body (cons 'do body)]
    (reduce (fn [body [sym expr]]
              (let [expr (list '.resolve 'js/Promise expr)]
                (list '.then expr (list 'clojure.core/fn (vector sym)
                                        body))))
            body
            binding-pairs)))

Using this macro we can look async code more like sync code. Consider this puppeteer example:

(-> (.launch puppeteer)
      (.then (fn [browser]
               (-> (.newPage browser)
                   (.then (fn [page]
                            (-> (.goto page "https://clojure.org")
                                (.then #(.screenshot page #js{:path "screenshot.png"}))
                                (.catch #(js/console.log %))
                                (.then #(.close browser)))))))))

Using plet this becomes:

(plet [browser (.launch puppeteer)
       page (.newPage browser)
       _ (.goto page "https://clojure.org")
       _ (-> (.screenshot page #js{:path "screenshot.png"})
             (.catch #(js/console.log %)))]
      (.close browser))

See the puppeteer example for the full code.

Since v0.0.36, nbb includes promesa which is a library to deal with promises. The above plet macro is similar to promesa.core/let.

Startup time

$ time nbb -e '(+ 1 2 3)'
6
nbb -e '(+ 1 2 3)'   0.17s  user 0.02s system 109% cpu 0.168 total

The baseline startup time for a script is about 170ms seconds on my laptop. When invoked via npx this adds another 300ms or so, so for faster startup, either use a globally installed nbb or use $(npm bin)/nbb script.cljs to bypass npx.

Dependencies

NPM dependencies

Nbb does not depend on any NPM dependencies. All NPM libraries loaded by a script are resolved relative to that script. When using the Reagent module, React is resolved in the same way as any other NPM library.

Classpath

To load .cljs files from local paths or dependencies, you can use the --classpath argument. The current dir is added to the classpath automatically. So if there is a file foo/bar.cljs relative to your current dir, then you can load it via (:require [foo.bar :as fb]). Note that nbb uses the same naming conventions for namespaces and directories as other Clojure tools: foo-bar in the namespace name becomes foo_bar in the directory name.

To load dependencies from the Clojure ecosystem, you can use the Clojure CLI or babashka to download them and produce a classpath:

$ classpath="$(clojure -A:nbb -Spath -Sdeps '{:aliases {:nbb {:replace-deps {com.github.seancorfield/honeysql {:git/tag "v2.0.0-rc5" :git/sha "01c3a55"}}}}}')"

and then feed it to the --classpath argument:

$ nbb --classpath "$classpath" -e "(require '[honey.sql :as sql]) (sql/format {:select :foo :from :bar :where [:= :baz 2]})"
["SELECT foo FROM bar WHERE baz = ?" 2]

Currently nbb only reads from directories, not jar files, so you are encouraged to use git libs. Support for .jar files will be added later.

Current file

The name of the file that is currently being executed is available via nbb.core/*file* or on the metadata of vars:

(ns foo
  (:require [nbb.core :refer [*file*]]))

(prn *file*) ;; "/private/tmp/foo.cljs"

(defn f [])
(prn (:file (meta #'f))) ;; "/private/tmp/foo.cljs"

Reagent

Nbb includes reagent.core which will be lazily loaded when required. You can use this together with ink to create a TUI application:

$ npm install ink

ink-demo.cljs:

(ns ink-demo
  (:require ["ink" :refer [render Text]]
            [reagent.core :as r]))

(defonce state (r/atom 0))

(doseq [n (range 1 11)]
  (js/setTimeout #(swap! state inc) (* n 500)))

(defn hello []
  [:> Text {:color "green"} "Hello, world! " @state])

(render (r/as-element [hello]))

Promesa

Working with callbacks and promises can become tedious. Since nbb v0.0.36 the promesa.core namespace is included with the let and do! macros. An example:

(ns prom
  (:require [promesa.core :as p]))

(defn sleep [ms]
  (js/Promise.
   (fn [resolve _]
     (js/setTimeout resolve ms))))

(defn do-stuff
  []
  (p/do!
   (println "Doing stuff which takes a while")
   (sleep 1000)
   1))

(p/let [a (do-stuff)
        b (inc a)
        c (do-stuff)
        d (+ b c)]
  (prn d))
$ nbb prom.cljs
Doing stuff which takes a while
Doing stuff which takes a while
3

Also see API docs.

Js-interop

Since nbb v0.0.75 applied-science/js-interop is available:

(ns example
  (:require [applied-science.js-interop :as j]))

(def o (j/lit {:a 1 :b 2 :c {:d 1}}))

(prn (j/select-keys o [:a :b])) ;; #js {:a 1, :b 2}
(prn (j/get-in o [:c :d])) ;; 1

Most of this library is supported in nbb, except the following:

  • destructuring using :syms
  • property access using .-x notation. In nbb, you must use keywords.

See the example of what is currently supported.

Examples

See the examples directory for small examples.

Also check out these projects built with nbb:

API

See API documentation.

Migrating to shadow-cljs

See this gist on how to convert an nbb script or project to shadow-cljs.

Build

Prequisites:

  • babashka >= 0.4.0
  • Clojure CLI >= 1.10.3.933
  • Node.js 16.5.0 (lower version may work, but this is the one I used to build)

To build:

  • Clone and cd into this repo
  • bb release

Run bb tasks for more project-related tasks.

Download Details:
Author: borkdude
Download Link: Download The Source Code
Official Website: https://github.com/borkdude/nbb 
License: EPL-1.0

#node #javascript

I am Developer

1618120954

Real Time Chat App using Node JS Express Socket IO

Real time chat with nodejs socket.io and expressjs. In this tutorial, you will learn how to build real time chat with nodejs socket.io, jquery and expressjs.

This tutorial will help you step by step to on how to build chat application using Nodejs, Express and Socket.IO.

How to build chat application using Nodejs, Express and Socket.IO

Follow the following steps and create chat application using Nodejs, Express and Socket.IO:

  • Step 1 - Create Chat App Directory
  • Step 2 - Install Node Express JS, Socket.io and jQuery
  • Step 3 - Create Index.html and Style.css
  • Step 4 - Create Chat.js
  • Step 5 - Create index.js
  • Step 6 - Run Development Server

https://www.tutsmake.com/node-js-express-socket-io-chat-application-example/

#node js chat application #node js chat application tutorial #real time chat with nodejs socket.io and expressjs #node js chat application with mysql

Node JS Development Company| Node JS Web Developers-SISGAIN

Top organizations and start-ups hire Node.js developers from SISGAIN for their strategic software development projects in Illinois, USA. On the off chance that you are searching for a first rate innovation to assemble a constant Node.js web application development or a module, Node.js applications are the most appropriate alternative to pick. As Leading Node.js development company, we leverage our profound information on its segments and convey solutions that bring noteworthy business results. For more information email us at hello@sisgain.com

#node.js development services #hire node.js developers #node.js web application development #node.js development company #node js application

Hire Dedicated Node.js Developers - Hire Node.js Developers

If you look at the backend technology used by today’s most popular apps there is one thing you would find common among them and that is the use of NodeJS Framework. Yes, the NodeJS framework is that effective and successful.

If you wish to have a strong backend for efficient app performance then have NodeJS at the backend.

WebClues Infotech offers different levels of experienced and expert professionals for your app development needs. So hire a dedicated NodeJS developer from WebClues Infotech with your experience requirement and expertise.

So what are you waiting for? Get your app developed with strong performance parameters from WebClues Infotech

For inquiry click here: https://www.webcluesinfotech.com/hire-nodejs-developer/

Book Free Interview: https://bit.ly/3dDShFg

#hire dedicated node.js developers #hire node.js developers #hire top dedicated node.js developers #hire node.js developers in usa & india #hire node js development company #hire the best node.js developers & programmers

Aria Barnes

Aria Barnes

1622719015

Why use Node.js for Web Development? Benefits and Examples of Apps

Front-end web development has been overwhelmed by JavaScript highlights for quite a long time. Google, Facebook, Wikipedia, and most of all online pages use JS for customer side activities. As of late, it additionally made a shift to cross-platform mobile development as a main technology in React Native, Nativescript, Apache Cordova, and other crossover devices. 

Throughout the most recent couple of years, Node.js moved to backend development as well. Designers need to utilize a similar tech stack for the whole web project without learning another language for server-side development. Node.js is a device that adjusts JS usefulness and syntax to the backend. 

What is Node.js? 

Node.js isn’t a language, or library, or system. It’s a runtime situation: commonly JavaScript needs a program to work, however Node.js makes appropriate settings for JS to run outside of the program. It’s based on a JavaScript V8 motor that can run in Chrome, different programs, or independently. 

The extent of V8 is to change JS program situated code into machine code — so JS turns into a broadly useful language and can be perceived by servers. This is one of the advantages of utilizing Node.js in web application development: it expands the usefulness of JavaScript, permitting designers to coordinate the language with APIs, different languages, and outside libraries.

What Are the Advantages of Node.js Web Application Development? 

Of late, organizations have been effectively changing from their backend tech stacks to Node.js. LinkedIn picked Node.js over Ruby on Rails since it took care of expanding responsibility better and decreased the quantity of servers by multiple times. PayPal and Netflix did something comparative, just they had a goal to change their design to microservices. We should investigate the motivations to pick Node.JS for web application development and when we are planning to hire node js developers. 

Amazing Tech Stack for Web Development 

The principal thing that makes Node.js a go-to environment for web development is its JavaScript legacy. It’s the most well known language right now with a great many free devices and a functioning local area. Node.js, because of its association with JS, immediately rose in ubiquity — presently it has in excess of 368 million downloads and a great many free tools in the bundle module. 

Alongside prevalence, Node.js additionally acquired the fundamental JS benefits: 

  • quick execution and information preparing; 
  • exceptionally reusable code; 
  • the code is not difficult to learn, compose, read, and keep up; 
  • tremendous asset library, a huge number of free aides, and a functioning local area. 

In addition, it’s a piece of a well known MEAN tech stack (the blend of MongoDB, Express.js, Angular, and Node.js — four tools that handle all vital parts of web application development). 

Designers Can Utilize JavaScript for the Whole Undertaking 

This is perhaps the most clear advantage of Node.js web application development. JavaScript is an unquestionable requirement for web development. Regardless of whether you construct a multi-page or single-page application, you need to know JS well. On the off chance that you are now OK with JavaScript, learning Node.js won’t be an issue. Grammar, fundamental usefulness, primary standards — every one of these things are comparable. 

In the event that you have JS designers in your group, it will be simpler for them to learn JS-based Node than a totally new dialect. What’s more, the front-end and back-end codebase will be basically the same, simple to peruse, and keep up — in light of the fact that they are both JS-based. 

A Quick Environment for Microservice Development 

There’s another motivation behind why Node.js got famous so rapidly. The environment suits well the idea of microservice development (spilling stone monument usefulness into handfuls or many more modest administrations). 

Microservices need to speak with one another rapidly — and Node.js is probably the quickest device in information handling. Among the fundamental Node.js benefits for programming development are its non-obstructing algorithms.

Node.js measures a few demands all at once without trusting that the first will be concluded. Many microservices can send messages to one another, and they will be gotten and addressed all the while. 

Versatile Web Application Development 

Node.js was worked in view of adaptability — its name really says it. The environment permits numerous hubs to run all the while and speak with one another. Here’s the reason Node.js adaptability is better than other web backend development arrangements. 

Node.js has a module that is liable for load adjusting for each running CPU center. This is one of numerous Node.js module benefits: you can run various hubs all at once, and the environment will naturally adjust the responsibility. 

Node.js permits even apportioning: you can part your application into various situations. You show various forms of the application to different clients, in light of their age, interests, area, language, and so on. This builds personalization and diminishes responsibility. Hub accomplishes this with kid measures — tasks that rapidly speak with one another and share a similar root. 

What’s more, Node’s non-hindering solicitation handling framework adds to fast, letting applications measure a great many solicitations. 

Control Stream Highlights

Numerous designers consider nonconcurrent to be one of the two impediments and benefits of Node.js web application development. In Node, at whatever point the capacity is executed, the code consequently sends a callback. As the quantity of capacities develops, so does the number of callbacks — and you end up in a circumstance known as the callback damnation. 

In any case, Node.js offers an exit plan. You can utilize systems that will plan capacities and sort through callbacks. Systems will associate comparable capacities consequently — so you can track down an essential component via search or in an envelope. At that point, there’s no compelling reason to look through callbacks.

 

Final Words

So, these are some of the top benefits of Nodejs in web application development. This is how Nodejs is contributing a lot to the field of web application development. 

I hope now you are totally aware of the whole process of how Nodejs is really important for your web project. If you are looking to hire a node js development company in India then I would suggest that you take a little consultancy too whenever you call. 

Good Luck!

Original Source

#node.js development company in india #node js development company #hire node js developers #hire node.js developers in india #node.js development services #node.js development