Node.js based smart shopping cart app
Information
In this page, there is English description followed by Japanese one.
本ページは英語の説明の後に日本語の説明が続きます。
Getting Started
Installing Node.js and npm
You need to have Node.js and npm installed.
To check if you have them installed, open a terminal or command prompt and run the following commands:
node --version npm --version
If you see an number output similar to x.x.x for each command, then they are both installed and you can continue to the next section.
To install on Windows or mac, you can download the installer from https://nodejs.org/en/download.
To install on Linux, you can use a package manager. Instructions for installing Node.js on your distribution can be found in the following link:
https://nodejs.org/en/download/package-manager
Prerequisite
This example assumes that you've already run the following program that can communicate the decoded result of barcode data with mbed Device Connector:
Import programGR-PEACH_mbed-os-client-ZXingSample
Fork of https://developer.mbed.org/teams/Renesas/code/GR-PEACH_mbed-os-client-ZXingSample/
Configuring the Applition
In order to run this app, you need to set up the options shown below via .env file stored in the folder GR-PEACH_mbed-os-QRCode-ShoppingCart-node which should be automatically created when cloning this program.
- ACCESS_KEY
Set this variable to your Access Key that you can create on mbed Device Connector. if you don't have an Access Key yet, please create it in accordance with the following procedure.
1. Access https://connector.mbed.com/#accesskeys.
2. Click CREATE NEW ACCESS KEY.
3. When prompted, enter a name for the access key (e.g. "demo") and click ADD.
After an access key is successfully created, please copy the access key you just created and use it in .env file as follows:
.env
ACCESS_KEY=...
- PORT
Set this variable as follows to override the default port for this example if needed. The default port is 8080.
.env
PORT=...
Also, user need to prepare for the comma-delimited list which includes "Item Name" and "Price" which is added to shopping cart, and save it by the name klist.txt as follows:
The list should be stored in GR-Peach_mbed-os_QRCode_ShoppingCart_node\public\list.
Application Execution
This application consists of 2 tabs. One is Shopping Cart and the other is QR Code Login. In this section, it is described that how those work.
As mentioned above, GR-PEACH_mbed-os-client-ZXingSample should be executed beforehand. For details on how to set up and execute GR-PEACH_mbed-os-client-ZXingSample, please refer to https://developer.mbed.org/teams/Renesas/code/GR-PEACH_mbed-os-client-ZXingSample/. If the program works properly, you can see the following message in your terminal:
After it is confirmed that the program works properly, please follow the procedure below in order to execute this Web Application.
- How to invoke this Web Application
You can now run the application by invoking the following:
Then, you should see the following message if the configuration is successfully done, :
Please note that 8080 might be changed. It should depends on your PORT setting mentioned above. If you access the above URL using Web browser, you can see the following Smart Shopping Cart tab by default:
- How Shopping Cart tab works
When you decode QR code stored in GR-Peach_mbed-os_QRCode_ShoppingCart_node\qrcode by GR-PEACH successfully, the item should be added to shopping cart as follows:
- How QR Code Login tab works
When you choose QR Code Login tab, you can see the following screen indicating it's Locked status.
Then, if you decode the Unlock qrcode described in GR-Peach_mbed-os_QRCode_ShoppingCart_node\qrcode\qr.pdf, screen should transit to the following one indicating it's Unlocked status.
After that if you you decode the Lock qrcode described in the above qr.pdf, screen should re-transit to Locked status. In this way, the screen transits to Locked and Unlocked status in accordance with the decoded result of QR code.
How to Deploy this app on HEROKU
HEROKU ( https://id.heroku.com ) is PaaS (Platform as a Service) on which Node.js application can deploy free-of charge. By utilizing it, you can access mbed Shopping Cart and QR Code Login from mobile terminal.
Here is the procedure to deploy this application on HEROKU:
- Create your HEROKU account at https://signup.heroku.com/login if you haven't created it yet.
- Install Heroku Toolbelt
32-bit: https://cli-assets.heroku.com/heroku-cli/channels/stable/heroku-cli-x86.exe
64-bit: https://cli-assets.heroku.com/heroku-cli/channels/stable/heroku-cli-x64.exe ) - Launch command prompt (e.g. Windows PowerShell) and move to the project root directory. Then, invoke the command heroku login. At the first time, Email and Password is thought to be required. At that time, please type Email address and password registered at the step 1.
- Invoke the command git init
- Invoke the command git add . to prepare all the files staged for the next commit
- Invoke the command git commit -m "[commit message]" to commit the files staged at the step 5
- Invoke the command heroku create. If the command is successfully terminated, the remote repository heroku should be created and associated with the local repository
- Invoke the command git push heroku master If the command is successfully terminated, this application should be deployed to HEROKU and its URL should be shown as follows:
remote: -----> Launching... remote: Released v3 remote: https://hogeoge.herokuapp.com/ deployed to Heroku
After all the steps are completed without error, please access the URL http:hogehoge.herokuapp.com/ (i.e URL where https in the URL shown in the step 7 is replaced with http) with Web browser. You should be able to show mbed Shopping Cart on Web browser.
-------------------------------------------------------------------------------------------------------------------------------------------------
Node.jsとnpmのインストール
本アプリケーションを実行するにあたっては、Node.jsとnpmのインストールが必要です。
お使いの開発環境(PC)にNode.js、npmがインストールされているかどうかは、下記コマンドで確認する事ができます。
node --version npm --version
上記コマンド実行後、x.x.x というバージョン・リビジョン番号が表示されれば、Node.js、npmは既にインストールされていますので、次節以降の手順にしたがってアプリケーションのセットアップを行ってください。未インストールの場合は以降の手順にしたがってNode.js、npmをインストールしてください。
開発環境のホストOSがWindowsまたはmacの場合はhttps://nodejs.org/en/download から入手可能なインストーラを使用してインストールします。
開発環境のホストOSがLinuxの場合は、お使いのディストリビーションに応じたパッケージ管理システムを用いたインストールが可能です。詳細はhttps://nodejs.org/en/download/package-manager を参照ください。
前提条件
本アプリケーションを実行するにあたっては、GR-PEACH上のバーコードデータのデコード結果にmbed Device Connectorからアクセスする下記プログラムを事前にセットアップしておく必要があります。
Import programGR-PEACH_mbed-os-client-ZXingSample
Fork of https://developer.mbed.org/teams/Renesas/code/GR-PEACH_mbed-os-client-ZXingSample/
アプリケーションの設定
本アプリケーションの実行するためには、.envファイルを介して以下に示すオプションを設定する必要があります。なお、.envファイルはGR-PEACH_mbed-os-QRCode-ShoppingCart-nodeフォルダに格納されています。
- ACCESS_KEY
本変数にはmbed Device Connector上で生成可能なAccess Keyを設定します。Access Keyが未生成の場合は下記に従って作成してください。
1. https://connector.mbed.com/#accesskeys にアクセスします。
2. CREATE NEW ACCESS KEYをクリックします。
3. access keyの名称を入力するように促されたら、任意の名称(例えばdemo等)を入力し、ADDをクリックします。
access keyが正常に生成できたら、コピーして下記のように.envファイルでACCESS_KEYに設定します。
.env
ACCESS_KEY=...
- PORT
本変数にはWebアプリへのアクセスに使用するポート番号を下記のように設定します。デフォルトのポート番号は 8080 です。8080から変更の必要がなければ、設定は省略可能です。
.env
PORT=...
また、ショッピングカートに追加する品目と値段をカンマ区切りで下記のように記載したリストを準備し、klist.txtという名称でGR-Peach_mbed-os_QRCode_ShoppingCart_node\public\listフォルダに格納してください。
アプリケーションの実行
本アプリケーションでは、Shopping CartとQR Code Loginという2つのタブが実装されています。以下、それぞれの動作方法について記載します。
なお上述の通り、本アプリケーションの実行に際しては、事前にGR-PEACH_mbed-os-client-ZXingSampleを実行しておく必要があります。GR-PEACH_mbed-os-client-ZXingSampleのセットアップ方法、および実行方法に関しては、https://developer.mbed.org/teams/Renesas/code/GR-PEACH_mbed-os-client-ZXingSample/ を参照ください。プログラムが正常に動作している場合、下記のメッセージがターミナルに表示されます。
プログラムの正常動作が確認できたら、以降の手順に従ってWebアプリケーションを実行します。
- Webアプリケーションの起動
下記コマンドでWebアプリケーションを起動可能です。
上述のアプリケーション設定が正常に行われていれば、下記メッセージが表示されます。
なお、8080はPORT設定に応じた値となります。
続いて、上述のURLにWebブラウザでアクセスすると、下記のSmart Shopping Cartの画面が表示されます。
- Shopping Cartタブ
GR-Peach_mbed-os_QRCode_ShoppingCart_node\qrcode\qrcode.pdf に記載されている Birthday Cake、Party Cups、Beer Kegs、Pound of beef、Buflle-proof vest のQRコードをデコードすると、下記のようにデコードしたアイテムが都度ショッピングカートに追加されます。
- QR Code Loginタブ
このタブを選択すると、下記のLock状態を示す画面が表示されます。
ここで、GR-Peach_mbed-os_QRCode_ShoppingCart_node\qrcode\qrcode.pdf に記載のUnlock QRコードをデコードすると、Unlock状態を示す下記の画面に遷移します。
この後、Lock QRコードをデコードすると画面はLock状態に再度遷移します。
このようにQR Code Loginタブでは、LockとUnlockのQRコードをデコードする都度、対応する画面に遷移するアプリケーションです。
HEROKUへのデプロイ
HEROKU ( https://id.heroku.com) はNode.jsアプリが無償でデプロイ可能なPaaS (Platform as a Service)と呼ばれるサービスです。HEROKUを活用する事で、mbed Shopping CartとQR Code Loginにモバイル端末等からアクセスする事が可能となります。
以下、HEROKUへ本アプリをデプロイする手順を説明します。
- HEROKUのアカウントを所有していない場合は https://signup.heroku.com/login でアカウントを作成してください
- Heroku Toolbeltをインストールします
32-bit版: https://cli-assets.heroku.com/heroku-cli/channels/stable/heroku-cli-x86.exe
64-bit版: https://cli-assets.heroku.com/heroku-cli/channels/stable/heroku-cli-x64.exe ) - ターミナルソフトウェア(例えばWindows PowerShell)を立上げます。そして本アプリのルートディレクトリへ移動し、heroku loginコマンドを実行します。Emailアドレスとパスワードの入力を求められた場合は、アカウント生成時に入力したアドレスとパスワードを入力してください。
- git initコマンドを実行します
- git add .コマンドを実行し、全ファイルをコミット対象に設定します
- git commit -m "[commit message]" で、全ファイルをコミットします
- heroku createを実行します。本コマンドが正常終了すると、リモートリポジトリ herokuが設定されます
- git push heroku master本コマンドが正常終了すると、HEROKUへのデプロイが完了し、下記のように本WebアプリのURLが表示されます
remote: -----> Launching... remote: Released v3 remote: https://hogeoge.herokuapp.com/ deployed to Heroku
上記の全ての手順が完了したら、http:hogehoge.herokuapp.com/ ( 8. で表示されたURL中のhttpsをhttpに置換えたもの)へブラウザ等でアクセスします。途中でエラーが発生していなければ、mbed Shopping CartがWebブラウザ上に表示されます。
Diff: node_modules/socket.io/Readme.md
- Revision:
- 0:a40b9a259b52
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/node_modules/socket.io/Readme.md Fri Jan 12 19:05:14 2018 +0900 @@ -0,0 +1,489 @@ + +# socket.io + +[![Build Status](https://secure.travis-ci.org/socketio/socket.io.svg?branch=master)](https://travis-ci.org/socketio/socket.io) +[![Dependency Status](https://david-dm.org/socketio/socket.io.svg)](https://david-dm.org/socketio/socket.io) +[![devDependency Status](https://david-dm.org/socketio/socket.io/dev-status.svg)](https://david-dm.org/socketio/socket.io#info=devDependencies) +[![NPM version](https://badge.fury.io/js/socket.io.svg)](https://www.npmjs.com/package/socket.io) +![Downloads](https://img.shields.io/npm/dm/socket.io.svg?style=flat) +[![](http://slack.socket.io/badge.svg?)](http://slack.socket.io) + +## How to use + +The following example attaches socket.io to a plain Node.JS +HTTP server listening on port `3000`. + +```js +var server = require('http').createServer(); +var io = require('socket.io')(server); +io.on('connection', function(client){ + client.on('event', function(data){}); + client.on('disconnect', function(){}); +}); +server.listen(3000); +``` + +### Standalone + +```js +var io = require('socket.io')(); +io.on('connection', function(client){}); +io.listen(3000); +``` + +### In conjunction with Express + +Starting with **3.0**, express applications have become request handler +functions that you pass to `http` or `http` `Server` instances. You need +to pass the `Server` to `socket.io`, and not the express application +function. + +```js +var app = require('express')(); +var server = require('http').createServer(app); +var io = require('socket.io')(server); +io.on('connection', function(){ /* … */ }); +server.listen(3000); +``` + +### In conjunction with Koa + +Like Express.JS, Koa works by exposing an application as a request +handler function, but only by calling the `callback` method. + +```js +var app = require('koa')(); +var server = require('http').createServer(app.callback()); +var io = require('socket.io')(server); +io.on('connection', function(){ /* … */ }); +server.listen(3000); +``` + +## API + +### Server + + Exposed by `require('socket.io')`. + +### Server() + + Creates a new `Server`. Works with and without `new`: + + ```js + var io = require('socket.io')(); + // or + var Server = require('socket.io'); + var io = new Server(); + ``` + +### Server(opts:Object) + + Optionally, the first or second argument (see below) of the `Server` + constructor can be an options object. + + The following options are supported: + + - `serveClient` sets the value for Server#serveClient() + - `path` sets the value for Server#path() + + The same options passed to socket.io are always passed to + the `engine.io` `Server` that gets created. See engine.io + [options](https://github.com/socketio/engine.io#methods-1) + as reference. + +### Server(srv:http#Server, opts:Object) + + Creates a new `Server` and attaches it to the given `srv`. Optionally + `opts` can be passed. + +### Server(port:Number, opts:Object) + + Binds socket.io to a new `http.Server` that listens on `port`. + +### Server#serveClient(v:Boolean):Server + + If `v` is `true` the attached server (see `Server#attach`) will serve + the client files. Defaults to `true`. + + This method has no effect after `attach` is called. + + ```js + // pass a server and the `serveClient` option + var io = require('socket.io')(http, { serveClient: false }); + + // or pass no server and then you can call the method + var io = require('socket.io')(); + io.serveClient(false); + io.attach(http); + ``` + + If no arguments are supplied this method returns the current value. + +### Server#path(v:String):Server + + Sets the path `v` under which `engine.io` and the static files will be + served. Defaults to `/socket.io`. + + If no arguments are supplied this method returns the current value. + +### Server#adapter(v:Adapter):Server + + Sets the adapter `v`. Defaults to an instance of the `Adapter` that + ships with socket.io which is memory based. See + [socket.io-adapter](https://github.com/socketio/socket.io-adapter). + + If no arguments are supplied this method returns the current value. + +### Server#origins(v:String):Server + + Sets the allowed origins `v`. Defaults to any origins being allowed. + + If no arguments are supplied this method returns the current value. + +### Server#origins(v:Function):Server + + Sets the allowed origins as dynamic function. Function takes two arguments `origin:String` and `callback(error, success)`, where `success` is a boolean value indicating whether origin is allowed or not. + + __Potential drawbacks__: + * in some situations, when it is not possible to determine `origin` it may have value of `*` + * As this function will be executed for every request, it is advised to make this function work as fast as possible + * If `socket.io` is used together with `Express`, the CORS headers will be affected only for `socket.io` requests. For Express can use [cors](https://github.com/expressjs/cors). + + +### Server#sockets:Namespace + + The default (`/`) namespace. + +### Server#attach(srv:http#Server, opts:Object):Server + + Attaches the `Server` to an engine.io instance on `srv` with the + supplied `opts` (optionally). + +### Server#attach(port:Number, opts:Object):Server + + Attaches the `Server` to an engine.io instance that is bound to `port` + with the given `opts` (optionally). + +### Server#listen + + Synonym of `Server#attach`. + +### Server#bind(srv:engine#Server):Server + + Advanced use only. Binds the server to a specific engine.io `Server` + (or compatible API) instance. + +### Server#onconnection(socket:engine#Socket):Server + + Advanced use only. Creates a new `socket.io` client from the incoming + engine.io (or compatible API) `socket`. + +### Server#of(nsp:String):Namespace + + Initializes and retrieves the given `Namespace` by its pathname + identifier `nsp`. + + If the namespace was already initialized it returns it immediately. + +### Server#emit + + Emits an event to all connected clients. The following two are + equivalent: + + ```js + var io = require('socket.io')(); + io.sockets.emit('an event sent to all connected clients'); + io.emit('an event sent to all connected clients'); + ``` + + For other available methods, see `Namespace` below. + +### Server#close([fn:Function]) + + Closes socket.io server. + + The optional `fn` is passed to the `server.close([callback])` method of the + core `net` module and is called on error or when all connections are closed. + The callback is expected to implement the common single argument `err` + signature (if any). + + ```js + var Server = require('socket.io'); + var PORT = 3030; + var server = require('http').Server(); + + var io = Server(PORT); + + io.close(); // Close current server + + server.listen(PORT); // PORT is free to use + + io = Server(server); + ``` + +### Server#use + + See `Namespace#use` below. + +### Namespace + + Represents a pool of sockets connected under a given scope identified + by a pathname (eg: `/chat`). + + By default the client always connects to `/`. + +#### Events + + - `connection` / `connect`. Fired upon a connection. + + Parameters: + - `Socket` the incoming socket. + +### Namespace#name:String + + The namespace identifier property. + +### Namespace#connected:Object<Socket> + + Hash of `Socket` objects that are connected to this namespace indexed + by `id`. + +### Namespace#clients(fn:Function) + + Gets a list of client IDs connected to this namespace (across all nodes if applicable). + + An example to get all clients in a namespace: + + ```js + var io = require('socket.io')(); + io.of('/chat').clients(function(error, clients){ + if (error) throw error; + console.log(clients); // => [PZDoMHjiu8PYfRiKAAAF, Anw2LatarvGVVXEIAAAD] + }); + ``` + + An example to get all clients in namespace's room: + + ```js + var io = require('socket.io')(); + io.of('/chat').in('general').clients(function(error, clients){ + if (error) throw error; + console.log(clients); // => [Anw2LatarvGVVXEIAAAD] + }); + ``` + + As with broadcasting, the default is all clients from the default namespace ('/'): + + ```js + var io = require('socket.io')(); + io.clients(function(error, clients){ + if (error) throw error; + console.log(clients); // => [6em3d4TJP8Et9EMNAAAA, G5p55dHhGgUnLUctAAAB] + }); + ``` + +### Namespace#use(fn:Function):Namespace + + Registers a middleware, which is a function that gets executed for + every incoming `Socket`, and receives as parameters the socket and a + function to optionally defer execution to the next registered + middleware. + + ```js + var io = require('socket.io')(); + io.use(function(socket, next){ + if (socket.request.headers.cookie) return next(); + next(new Error('Authentication error')); + }); + ``` + + Errors passed to middleware callbacks are sent as special `error` + packets to clients. + +### Socket + + A `Socket` is the fundamental class for interacting with browser + clients. A `Socket` belongs to a certain `Namespace` (by default `/`) + and uses an underlying `Client` to communicate. + + It should be noted the `Socket` doesn't relate directly to the actual + underlying TCP/IP `socket` and it is only the name of the class. + +### Socket#use(fn:Function):Socket + + Registers a middleware, which is a function that gets executed for + every incoming `Packet` and receives as parameter the packet and a + function to optionally defer execution to the next registered + middleware. + + ```js + var io = require('socket.io')(); + io.on('connection', function(socket){ + socket.use(function(packet, next){ + if (packet.doge === true) return next(); + next(new Error('Not a doge error')); + }); + ``` + + Errors passed to middleware callbacks are sent as special `error` + packets to clients. + +### Socket#rooms:Object + + A hash of strings identifying the rooms this client is in, indexed by + room name. + +### Socket#client:Client + + A reference to the underlying `Client` object. + +### Socket#conn:Socket + + A reference to the underlying `Client` transport connection (engine.io + `Socket` object). This allows access to the IO transport layer, which + still (mostly) abstracts the actual TCP/IP socket. + +### Socket#request:Request + + A getter proxy that returns the reference to the `request` that + originated the underlying engine.io `Client`. Useful for accessing + request headers such as `Cookie` or `User-Agent`. + +### Socket#id:String + + A unique identifier for the session, that comes from the + underlying `Client`. + +### Socket#emit(name:String[, …]):Socket + + Emits an event identified by the string `name` to the client. + Any other parameters can be included. + + All datastructures are supported, including `Buffer`. JavaScript + functions can't be serialized/deserialized. + + ```js + var io = require('socket.io')(); + io.on('connection', function(client){ + client.emit('an event', { some: 'data' }); + }); + ``` + +### Socket#join(name:String[, fn:Function]):Socket + + Adds the client to the `room`, and fires optionally a callback `fn` + with `err` signature (if any). + + The client is automatically a member of a room identified with its + session id (see `Socket#id`). + + The mechanics of joining rooms are handled by the `Adapter` + that has been configured (see `Server#adapter` above), defaulting to + [socket.io-adapter](https://github.com/socketio/socket.io-adapter). + +### Socket#leave(name:String[, fn:Function]):Socket + + Removes the client from `room`, and fires optionally a callback `fn` + with `err` signature (if any). + + **Rooms are left automatically upon disconnection**. + + The mechanics of leaving rooms are handled by the `Adapter` + that has been configured (see `Server#adapter` above), defaulting to + [socket.io-adapter](https://github.com/socketio/socket.io-adapter). + +### Socket#to(room:String):Socket + + Sets a modifier for a subsequent event emission that the event will + only be _broadcasted_ to clients that have joined the given `room`. + + To emit to multiple rooms, you can call `to` several times. + + ```js + var io = require('socket.io')(); + io.on('connection', function(client){ + client.to('others').emit('an event', { some: 'data' }); + }); + ``` + +### Socket#in(room:String):Socket + + Same as `Socket#to` + +### Socket#compress(v:Boolean):Socket + + Sets a modifier for a subsequent event emission that the event data will + only be _compressed_ if the value is `true`. Defaults to `true` when you don't call the method. + + ```js + var io = require('socket.io')(); + io.on('connection', function(client){ + client.compress(false).emit('an event', { some: 'data' }); + }); + ``` + +### Socket#disconnect(close:Boolean):Socket + + Disconnects this client. If value of close is `true`, closes the underlying connection. + Otherwise, it just disconnects the namespace. + +#### Events + +- `disconnect` + - Fired upon disconnection. + - **Arguments** + - `String`: the reason of the disconnection (either client or server-side) +- `error` + - Fired when an error occurs. + - **Arguments** + - `Object`: error data +- `disconnecting` + - Fired when the client is going to be disconnected (but hasn't left its `rooms` yet). + - **Arguments** + - `String`: the reason of the disconnection (either client or server-side) + +These are reserved events (along with `connect`, `newListener` and `removeListener`) which cannot be used as event names. + + +### Client + + The `Client` class represents an incoming transport (engine.io) + connection. A `Client` can be associated with many multiplexed `Socket`s + that belong to different `Namespace`s. + +### Client#conn + + A reference to the underlying `engine.io` `Socket` connection. + +### Client#request + + A getter proxy that returns the reference to the `request` that + originated the engine.io connection. Useful for accessing + request headers such as `Cookie` or `User-Agent`. + +## Debug / logging + +Socket.IO is powered by [debug](https://github.com/visionmedia/debug). +In order to see all the debug output, run your app with the environment variable +`DEBUG` including the desired scope. + +To see the output from all of Socket.IO's debugging scopes you can use: + +``` +DEBUG=socket.io* node myapp +``` + +## Testing + +``` +npm test +``` +This runs the `gulp` task `test`. By default the test will be run with the source code in `lib` directory. + +Set the environmental variable `TEST_VERSION` to `compat` to test the transpiled es5-compat version of the code. + +The `gulp` task `test` will always transpile the source code into es5 and export to `dist` first before running the test. + +## License + +[MIT](LICENSE)