Getting started with Node.jsnpmWeb Apps With ExpressFilesystem I/OExporting and Consuming ModulesExporting and Importing Module in node.jsInstalling Node.jsMySQL integrationReadlinepackage.jsonEvent EmittersAutoreload on changesEnvironmentCallback to PromiseExecuting files or commands with Child ProcessesCluster ModuleException handlingKeep a node application constantly runningUninstalling Node.jsnvm - Node Version ManagerhttpUsing StreamsDeploying Node.js applications in productionSecuring Node.js applicationsMongoose Libraryasync.jsFile uploadSocket.io communicationMongodb integrationHandling POST request in Node.jsSimple REST based CRUD APITemplate frameworksNode.js Architecture & Inner WorkingsDebugging Node.js applicationNode server without frameworkNode.JS with ES6Interacting with ConsoleCassandra IntegrationCreating API's with Node.jsGraceful ShutdownUsing IISNode to host Node.js Web Apps in IISCLINodeJS FrameworksgruntUsing WebSocket's with Node.JSmetalsmithParsing command line argumentsClient-server communicationNode.js Design FundamentalConnect to MongodbPerformance challengesSend Web NotificationRemote Debugging in Node.JSMysql Connection PoolDatabase (MongoDB with Mongoose)Good coding styleRestful API Design: Best PracticesDeliver HTML or any other sort of fileTCP SocketsHackBluebird PromisesAsync/AwaitKoa Framework v2Unit testing frameworksECMAScript 2015 (ES6) with Node.jsRouting ajax requests with Express.JSSending a file stream to clientNodeJS with RedisUsing Browserfiy to resolve 'required' error with browsersNode.JS and MongoDB.Passport integrationDependency InjectionNodeJS Beginner GuideUse Cases of Node.jsSequelize.jsPostgreSQL integrationHow modules are loadedNode.js with OracleSynchronous vs Asynchronous programming in nodejsNode.js Error ManagementNode.js v6 New Features and ImprovementEventloopNodejs Historypassport.jsAsynchronous programmingNode.js code for STDIN and STDOUT without using any libraryMongoDB Integration for Node.js/Express.jsLodashcsv parser in node jsLoopback - REST Based connectorRunning node.js as a serviceNode.js with CORSGetting started with Nodes profilingNode.js PerformanceYarn Package ManagerOAuth 2.0Node JS LocalizationDeploying Node.js application without downtime.Node.js (express.js) with angular.js Sample codeNodeJs RoutingCreating a Node.js Library that Supports Both Promises and Error-First CallbacksMSSQL IntergrationProject StructureAvoid callback hellArduino communication with nodeJsN-APIMultithreadingWindows authentication under node.jsRequire()Route-Controller-Service structure for ExpressJSPush notifications

Send Web Notification

Other topics

Send Web notification using GCM ( Google Cloud Messaging System)

Such Example is knowing wide spreading among PWAs (Progressive Web Applications) and in this example we're going to send a simple Backend like notification using NodeJS and ES6

  1. Install Node-GCM Module : npm install node-gcm

  2. Install Socket.io : npm install socket.io

  3. Create a GCM Enabled application using Google Console.

  4. Grabe your GCM Application Id (we will need it later on)

  5. Grabe your GCM Application Secret code.

  6. Open Your favorite code editor and add the following code :

     'use strict';
    
     const express = require('express');
     const app = express();
     const gcm = require('node-gcm');
     app.io = require('socket.io')();
     
     // [*] Configuring our GCM Channel.
     const sender = new gcm.Sender('Project Secret');
     const regTokens = [];
     let message = new gcm.Message({
         data: {
             key1: 'msg1'
         }
     });
     
     // [*] Configuring our static files.
     app.use(express.static('public/'));
     
     // [*] Configuring Routes.
     app.get('/', (req, res) => {
         res.sendFile(__dirname + '/public/index.html');
     });
     
     // [*] Configuring our Socket Connection.
     app.io.on('connection', socket => {
         console.log('we have a new connection ...');
         socket.on('new_user', (reg_id) => {
             // [*] Adding our user notification registration token to our list typically hided in a secret place.
             if (regTokens.indexOf(reg_id) === -1) {
                 regTokens.push(reg_id);
     
                 // [*] Sending our push messages
                 sender.send(message, {
                     registrationTokens: regTokens
                 }, (err, response) => {
                     if (err) console.error('err', err);
                     else console.log(response);
                 });
             }
         })
     });
      
     module.exports = app
    

PS : I'm using here a special hack in order to make Socket.io works with Express because simply it doesn't work outside of the box.

Now Create a .json file and name it : Manifest.json, open it and past the following :

{
    "name": "Application Name",
    "gcm_sender_id": "GCM Project ID"
}

Close it and save in your application ROOT directory.

PS : the Manifest.json file needs to be in root directory or it won't work.

In the code above I'm doing the following :

  1. I seted up and sent a normal index.html page that will use socket.io also.
  2. I'm listening on a connection event fired from the front-end aka my index.html page (it will be fired once a new client successfully connected to our pre-defined link)
  3. I'm sending a special token know's as the registration token from my index.html via socket.io new_user event, such token will be our user unique passcode and each code is generated usually from a supporting browser for the Web notification API (read more here.
  4. I'm simply using the node-gcm module to send my notification which will be handled and shown later on using Service Workers`.

This is from NodeJS point of view. in other examples I will show how we can send custom data, icons ..etc in our push message.

PS : you can find the full working demo over here.

Contributors

Topic Id: 6333

Example Ids: 21855

This site is not affiliated with any of the contributors.