Category Archives: JavaScript / Ajax

node.js + mqtt (Docker)

Directory Path : /app

Dockerfile

FROM node:latest
# 
WORKDIR specifies the directory our
# application's code will live within
WORKDIR /app
# We copy our package.json file to our
# app directory

RUN npm install -g nodemon

COPY package.json /app/package.json
# We then run npm install to install
# express for our application
RUN npm install && npm ls
RUN mv /app/node_modules /node_modules

# We then copy the rest of our application
# to the app direcoty
COPY . /app
# We start our application by calling
# npm start.
CMD ["npm", "start"]

mqtt-server.js

var mqtt = require('mqtt');
var fs = require('fs');
var path = require('path');

var clientID = "HKOSub"+Math.random().toString(36).substring(7);

var TRUSTED_CA_LIST = fs.readFileSync(path.join(__dirname, './key.pem'));

var address = '127.0.0.1';
var PORT = 1883;

const options = {
    host: address,
    port: PORT,
    keepalive: 60,
    clientId: clientID,
    // username: "testing_user",
    // password: "password",
    // protocol: 'mqtts',
    // rejectUnauthorized: true,
    // ca: TRUSTED_CA_LIST
};

var client = mqtt.connect(options);
var topic="name/#"
client.subscribe(topic, {  //subscribe to /[SI]/[DI]/raw/json
    qos: 1
});

client.on('message', function (topic, message) {
    console.log("[Received] topic: " + topic.toString());  //Print topic name
    console.log("[Received] message: " + message.toString()); //Print payload
})

function publishdata() {
  client.publish('LEUNG/test/time', 'Current time is: ' + new Date());
}

//setInterval(publishdata, 5000); //publish data every 10 seconds

package.json

{
    "name": "mqtt",
    "version": "1.0.0",
    "main": "mqtt-server.js",
    "dependencies": {
      "express" : "^4.16.3",
      "mqtt" : ""
    },
    "scripts": {
      "start": "node mqtt-server.js"
    }
  }

Docker

Docker build -t mqtt-server .

docker run -it -p 9001:3000 -v $(pwd):/app mqtt-server

Automatically Picking up Changes in node.js (Docker)

Location Dir Path : /app

app.js

const express = require("express");
const app = express();

app.get("/", (req, res) => res.send(`Hello World!`));

app.listen(3000, () => {
  console.log(`Example app listening on port 3000!`);
});

Dockerfile

FROM node:latest
# 
WORKDIR specifies the directory our
# application's code will live within
WORKDIR /app
# We copy our package.json file to our
# app directory
RUN npm install -g nodemon
COPY package.json /app/package.json
# We then run npm install to install
# express for our application
RUN npm install && npm ls
RUN mv /app/node_modules /node_modules
# We then copy the rest of our application
# to the app direcoty
COPY . /app
# We start our application by calling
# npm start.
CMD ["npm", "start"]

package.json

{
    "name": "hello-world",
    "version": "1.0.0",
    "main": "app.js",
    "dependencies": {
      "express" : "^4.16.3"
    },
    "scripts": {
      "start": "node app.js"
    }
}

Docker:

docker build -t node-docker-tutorial .

docker run -it -p 9001:3000 -v $(pwd):/app node-docker-tutorial

Output :
http://127.0.0.1:9001 Hello World

automatically-picking-up-changes-in-node-js-docker

Docker + node.js

Location Dir Path : /app

app.js

const express = require("express");
const app = express();

app.get("/", (req, res) => res.send(`Hello World!`));

app.listen(3000, () => {
  console.log(`Example app listening on port 3000!`);
});

Dockerfile

FROM node:latest
# Create app directory
WORKDIR /app
# Copy package.json and package-lock.json using a wildcard
COPY package*.json ./
# Install app dependencies
RUN npm install
# Bundle app source
COPY . ./app
EXPOSE 8080
CMD ["npm", "start"]

package.json

{
    "name": "simple-rest-api",
    "version": "1.0.0",
    "main": "app.js",
    "dependencies": {
      "express": "^4.16.3"
    },
    "scripts": {
      "start": "node app.js"
    }
}

Building our Docker Image

docker build -t node-docker .

docker run -d -p 9000:3000 node-docker

Output :
127.0.0.1:9000 Hello World!

Docker + node.js

addLayer in OpenLayer

<!doctype html>
<html lang="en">
  <head>
    <meta charset="utf-8">
	<link rel="stylesheet" href="https://cdn.rawgit.com/openlayers/openlayers.github.io/master/en/v5.3.0/css/ol.css">
    <script src="https://cdn.rawgit.com/openlayers/openlayers.github.io/master/en/v5.3.0/build/ol.js"></script>
	<style>
      .map {
        height: 100%;
        width: 100%;
		
      }
      .ol-popup {
        position: absolute;
        background-color: white;
        -webkit-filter: drop-shadow(0 1px 4px rgba(0,0,0,0.2));
        filter: drop-shadow(0 1px 4px rgba(0,0,0,0.2));
        padding: 15px;
        border-radius: 10px;
        border: 1px solid #cccccc;
        bottom: 12px;
        left: -50px;
      }
      .ol-popup:after, .ol-popup:before {
        top: 100%;
        border: solid transparent;
        content: " ";
        height: 0;
        width: 0;
        position: absolute;
        pointer-events: none;
      }
      .ol-popup:after {
        border-top-color: white;
        border-width: 10px;
        left: 48px;
        margin-left: -10px;
      }
      .ol-popup:before {
        border-top-color: #cccccc;
        border-width: 11px;
        left: 48px;
        margin-left: -11px;
      }
      .ol-popup-closer {
        text-decoration: none;
        position: absolute;
        top: 2px;
        right: 8px;
      }
      .ol-popup-closer:after {
        content: "✖";
      }
    </style>
  <title>OpenLayers 3 example</title>
  </head>
  <body>
    <div id="map" class="map">
        <div id="popup" class="ol-popup">
            <a href="#" id="popup-closer" class="ol-popup-closer"></a>
            <div id="popup-content" style="width:300px; height:120px;"></div>
        </div>
    </div> 
	<script type="text/javascript">
		/**
		* Elements that make up the popup.
		*/
		var container = document.getElementById('popup');
		var content = document.getElementById('popup-content');
		var closer = document.getElementById('popup-closer');

		/**
		* Add a click handler to hide the popup.
		* @return {boolean} Don't follow the href.
		*/
		closer.onclick = function() {
			overlay.setPosition(undefined);
			closer.blur();
			return false;
		};

		/**
		* Create an overlay to anchor the popup to the map.
		*/
		var overlay = new ol.Overlay(/** @type {olx.OverlayOptions} */ ({
			element: container,
			autoPan: true,
			autoPanAnimation: {
				duration: 250 // 當彈出超出地圖邊界時,為了彈出全部可見,地圖移動的速度。單位為毫秒(ms)
			}
		}));
	
		map = new ol.Map({
			target: 'map',
			layers: [
					new ol.layer.Tile({
						source: new ol.source.OSM()
					})
				],
			view: new ol.View({
			  center: ol.proj.transform([114.17232, 22.29958], 'EPSG:4326', 'EPSG:3857'),
			  zoom: 15
			})
		});
		
		var vectorLayer1 = new ol.layer.Vector({
			source:new ol.source.Vector({
				features: [new ol.Feature({
					geometry: new ol.geom.Point(ol.proj.transform([parseFloat(114.17232), parseFloat(22.29958)], 'EPSG:4326', 'EPSG:3857')),
				})]
			}),
			style: new ol.style.Style({
				image: new ol.style.Icon({
					anchor: [0.5, 0.5],
					anchorXUnits: "fraction",
					anchorYUnits: "fraction",
					src: "https://upload.wikimedia.org/wikipedia/commons/e/ec/RedDot.svg"
				})
			})
		});
		map.addLayer(vectorLayer1); 
		
		var vectorLayer2 = new ol.layer.Vector({
			source:new ol.source.Vector({
				features: [new ol.Feature({
					geometry: new ol.geom.Point(ol.proj.transform([parseFloat(114.1704), parseFloat(22.3012)], 'EPSG:4326', 'EPSG:3857')),
				})]
			}),
			style: new ol.style.Style({
				image: new ol.style.Icon({
					anchor: [0.5, 0.5],
					anchorXUnits: "fraction",
					anchorYUnits: "fraction",
					src: "https://upload.wikimedia.org/wikipedia/commons/e/ec/RedDot.svg"
				})
			})
		});
		map.addLayer(vectorLayer2); 

		/**
		* Add a click handler to the map to render the popup.
		*/
		map.on('click', function(e) {
			var feature = map.forEachFeatureAtPixel(e.pixel, function(feature) {
				return feature;
			});
			map.forEachFeatureAtPixel(e.pixel, function(feature, layer) {
			    if (layer === vectorLayer1) {
					var coordinate = e.coordinate;
					var hdms = ol.coordinate.toStringHDMS(ol.proj.transform(
					coordinate, 'EPSG:3857', 'EPSG:4326'));
					content.innerHTML = '<p>A:</p><code>' + hdms + '</code>';
					overlay.setPosition(coordinate);
					map.addOverlay(overlay);
				}else if (layer === vectorLayer2) {
					var coordinate = e.coordinate;
					var hdms = ol.coordinate.toStringHDMS(ol.proj.transform(
					coordinate, 'EPSG:3857', 'EPSG:4326'));
					content.innerHTML = '<p>B:</p><code>' + hdms + '</code>';
					overlay.setPosition(coordinate);
					map.addOverlay(overlay);
				}
			});
		});
	</script>
  </body>
</html>

openlayer-map

OpenLayer – Map

<!doctype html>
<html lang="en">
  <head>
    <script src="https://cdn.rawgit.com/openlayers/openlayers.github.io/master/en/v5.3.0/build/ol.js"></script>
    <link rel="stylesheet" href="https://cdn.rawgit.com/openlayers/openlayers.github.io/master/en/v5.3.0/css/ol.css">
    <style>
      .map {
        height: 100%;
        width: 100%;
      }
    </style>
    <title>OpenLayers example</title>
  </head>
  <body>
    <div id="map" class="map"></div>
    <script type="text/javascript">
      var map = new ol.Map({
        target: 'map',
        layers: [
          new ol.layer.Tile({
            source: new ol.source.OSM()
          })
        ],
        view: new ol.View({
		center: ol.proj.transform([114.17232, 22.29958], 'EPSG:4326', 'EPSG:3857'),
		zoom: 16
        })
      });
    </script>
  </body>
</html>

openlayer-map