Thursday, February 16, 2017

Javascript vs Clipper/Harbour vs Delphi (Object Pascal)

After deciding to program for nodejs, I started to learn Javascript from scratch and discovered that there are striking similarities with Clipper/Harbour and a bit with Delphi

Similarities

Comments
Javascript, Clipper/Harbour and Delphi supports comments after:

//

/*  */

Differences

Case Sensitivity
Clipper/Harbour, Delphi 
 - case insensitive\

Javascript
- case sensitive, lower case


Variable Typing :
Clipper/Harbour
- strongly typed

Javascript 
- Weakly typed

End of Statement
Javascript
- semi-colon marks end of atatement

Clipper/Harbour -
 No need


FUNCTION Structure

Clipper/Harbour :

FUNCTION  <name> (var1)

RETURN

Javascript :

function <name> (var1 {

return var1 ;
}



More to come...


Wednesday, February 15, 2017

Simple Meteor App

C:\Node4Meteor>meteor create simple-todos
Created a new Meteor app in 'simple-todos'.

To run your new app:
  cd simple-todos
  meteor npm install
  meteor

If you are new to Meteor, try some of the learning resources here:
  https://www.meteor.com/learn

meteor create --bare to create an empty app.
meteor create --full to create a scaffolded app.


C:\Node4Meteor>cd simple-todos

C:\Node4Meteor\simple-todos>dir
 Volume in drive C has no label.
 Volume Serial Number is 5449-2F7F

 Directory of C:\Node4Meteor\simple-todos

15-Feb-17  09:48 PM    <DIR>          .
15-Feb-17  09:48 PM    <DIR>          ..
15-Feb-17  09:48 PM                14 .gitignore
15-Feb-17  09:52 PM    <DIR>          .meteor
15-Feb-17  09:48 PM    <DIR>          client
15-Feb-17  09:48 PM               184 package.json
15-Feb-17  09:48 PM    <DIR>          server
               2 File(s)            198 bytes
               5 Dir(s)  181,786,734,592 bytes free

C:\Node4Meteor\simple-todos>meteor npm install
simple-todos@ C:\Node4Meteor\simple-todos
+-- babel-runtime@6.18.0
| +-- core-js@2.4.1
| `-- regenerator-runtime@0.9.6
`-- meteor-node-stubs@0.2.5
  +-- asn1.js@4.9.0
  +-- assert@1.4.1
  +-- Base64@0.2.1
  +-- base64-js@1.2.0
  +-- bn.js@4.11.6
  +-- brorand@1.0.6
  +-- browserify-aes@1.0.6
  +-- browserify-cipher@1.0.0
  +-- browserify-des@1.0.0
  +-- browserify-rsa@4.0.1
  +-- browserify-sign@4.0.0
  +-- browserify-zlib@0.1.4
  +-- buffer@4.9.1
  +-- buffer-shims@1.0.0
  +-- buffer-xor@1.0.3
  +-- cipher-base@1.0.3
  +-- console-browserify@1.1.0
  +-- constants-browserify@1.0.0
  +-- core-util-is@1.0.2
  +-- create-ecdh@4.0.0
  +-- create-hash@1.1.2
  +-- create-hmac@1.1.4
  +-- crypto-browserify@3.11.0
  +-- date-now@0.1.4
  +-- des.js@1.0.0
  +-- diffie-hellman@5.0.2
  +-- domain-browser@1.1.7
  +-- elliptic@6.3.2
  +-- events@1.1.1
  +-- evp_bytestokey@1.0.0
  +-- hash.js@1.0.3
  +-- http-browserify@1.7.0
  +-- https-browserify@0.0.1
  +-- ieee754@1.1.8
  +-- indexof@0.0.1
  +-- inherits@2.0.1
  +-- isarray@1.0.0
  +-- miller-rabin@4.0.0
  +-- minimalistic-assert@1.0.0
  +-- os-browserify@0.2.1
  +-- pako@0.2.9
  +-- parse-asn1@5.0.0
  +-- path-browserify@0.0.0
  +-- pbkdf2@3.0.9
  +-- process@0.11.9
  +-- process-nextick-args@1.0.7
  +-- public-encrypt@4.0.0
  +-- punycode@1.4.1
  +-- querystring@0.2.0
  +-- querystring-es3@0.2.1
  +-- randombytes@2.0.3
  +-- readable-stream@2.2.1
  +-- ripemd160@1.0.1
  +-- sha.js@2.4.8
  +-- stream-browserify@2.0.1
  +-- string_decoder@0.10.31
  +-- timers-browserify@1.4.2
  +-- tty-browserify@0.0.0
  +-- url@0.11.0
  | `-- punycode@1.3.2
  +-- util@0.10.3
  +-- util-deprecate@1.0.2
  `-- vm-browserify@0.0.4


C:\Node4Meteor\simple-todos>

C:\Node4Meteor\simple-todos>meteor
[[[[[ C:\Node4Meteor\simple-todos ]]]]]

=> Started proxy.
=> Started MongoDB.
=> Started your app.

=> App running at: http://localhost:3000/
   Type Control-C twice to stop.

Tuesday, February 14, 2017

How to create a simple web server using Nodejs

Example#

An example of a web server written with Node.js which responds with 'Hello World':
const http = require('http');

const hostname = '127.0.0.1';
const port = 3000;

const server = http.createServer((req, res) => {
  res.statusCode = 200;
  res.setHeader('Content-Type', 'text/plain');
  res.end('Hello World\n');
});

server.listen(port, hostname, () => {
  console.log(`Server running at http://${hostname}:${port}/`);
});
To run the server, put the code into a file called example.js and execute it with Node.js:
$ node example.js
Server running at http://127.0.0.1:3000/

Monday, February 13, 2017

geddy Project

1. Installation

npm install -g geddy

2. Building an App

geddy gen app task

3. Starting geddy Server

C:\Node4Geddy>cd task

C:\Node4Geddy\task>geddy
[Mon, 13 Feb 2017 12:38:57 GMT] INFO Server starting with config: {
  "environment": "development",
  "workers": 1,
  "port": 4000,
  "spdy": null,
  "ssl": null,
  "detailedErrors": true,
  "requestTimeout": null,
  "flash": {
    "defaultClass": "alert",
    "inlineClasses": {
      "success": "alert alert-success",
      "alert": "alert",
      "error": "alert alert-error",
      "info": "alert alert-info"
    },
    "blockClasses": {
      "success": "alert alert-block alert-success",
      "alert": "alert alert-block",
      "error": "alert alert-block alert-error",
      "info": "alert alert-block alert-info"
    }
  },
  "debug": true,
  "watch": {
    "files": [
      "/config",
      "/lib",
      "/app/controllers",
      "/app/models",
      "/app/views",
      "/app/helpers"
    ],
    "includePattern": "\\.(js|coffee|css|less|scss)$",
    "excludePattern": "\\.git|node_modules"
  },
  "rotateWorkers": false,
  "rotationWindow": 7200000,
  "rotationTimeout": 300000,
  "logDir": "C:\\Node4Geddy\\task\\log",
  "gracefulShutdownTimeout": 30000,
  "heartbeatInterval": 5000,
  "heartbeatWindow": 20000,
  "staticFilePath": "C:\\Node4Geddy\\task\\public",
  "assetHost": "",
  "assetBasePath": "/",
  "cacheControl": {
    "expires": {
      "default": 0
    }
  },
  "sessions": {
    "store": "filesystem",
    "key": "sid",
    "expiry": 1209600,
    "filename": "_session_store.json"
  },
  "cookieSessionKey": "sdata",
  "i18n": {
    "defaultLocale": "en-us",
    "loadPaths": [
      "C:\\Node4Geddy\\task\\config\\locales"
    ]
  },
  "appName": "Geddy App (development)",
  "hostname": null,
  "fullHostname": null,
  "connectCompatibility": false,
  "mailer": null,
  "generatedByVersion": "13.0.8",
  "model": {
    "defaultAdapter": "filesystem"
  }
}
[Mon, 13 Feb 2017 12:38:57 GMT] INFO Creating 1 worker process.
[Mon, 13 Feb 2017 12:38:57 GMT] INFO Server worker running in development on por
t 4000 with a PID of: 3704

4. Scaffolding Resources

geddy gen  scaffold task title:default status

C:\Node4Geddy\task>geddy gen scaffold step title:default description:text status

[Added] app\models\step.js
[Added] db\migrations\20170213204944_create_steps.js
[Added] test\models\step.js
[Added] test\controllers\steps.js
[Added] app\controllers\steps.js
[Added] Resource steps route added to config\router.js
[Added] View templates

C:\Node4Geddy\task>


5. Add Validations

var ToDo = function () { ... // Add this inside the constructor function this.validatesPresent('title'); this.validatesLength('title', {min: 5}); this.validatesWithFunction('status', function (status) { return status == 'open' || status == 'done'; }, {message: "Status must be 'open' or 'done.'"}); ... }; ToDo = geddy.model.register('ToDo', ToDo);

6. Create Associations

var ToDo = function () { ... this.hasMany('Steps'); ... };

var Step = function () { ... this.belongsTo('ToDo'); ... }; Step = geddy.model.register('Step', Step);

Sunday, February 12, 2017

Express-Compound Project

C:\Node4Compound>npm install -g compound

npm WARN deprecated jade@0.26.3: Jade has been renamed to pug, please install th
e latest version of pug instead of jade
npm WARN deprecated graceful-fs@2.0.3: graceful-fs v3.0.0 and before will fail o
n node releases >= v7.0. Please update to graceful-fs@^4.0.0 as soon as possible
. Use 'npm ls graceful-fs' to find it in the tree.
npm WARN deprecated minimatch@0.2.14: Please update to minimatch 3.0.2 or higher
 to avoid a RegExp DoS issue
C:\Users\User\AppData\Roaming\npm\compound -> C:\Users\User\AppData\Roaming\npm\
node_modules\compound\bin\compound.js
C:\Users\User\AppData\Roaming\npm\rw -> C:\Users\User\AppData\Roaming\npm\node_m
odules\compound\bin\compound.js
C:\Users\User\AppData\Roaming\npm
`-- compound@1.2.4


C:\Node4Compound>compound init todo -coffee -tpl pug
create  todo
create  todo\app\
create  todo\app\assets\
create  todo\app\assets\coffeescripts\
create  todo\app\assets\stylesheets\
create  todo\app\models\
create  todo\app\controllers\
create  todo\app\helpers\
create  todo\app\tools\
create  todo\app\views\
create  todo\app\views\layouts\
create  todo\db\
create  todo\db\seeds\
create  todo\db\seeds\development\
create  todo\log\
create  todo\public\
create  todo\public\images
create  todo\public\stylesheets\
create  todo\public\javascripts\
create  todo\node_modules\
create  todo\config\
create  todo\config\locales\
create  todo\config\initializers\
create  todo\config\environments\
create  todo\app\assets\coffeescripts\application.coffee
create  todo\app\assets\stylesheets\application.styl
create  todo\app\tools\database.js
create  todo\config\environment.js
create  todo\config\environments\development.js
create  todo\config\environments\production.js
create  todo\config\environments\test.js
create  todo\config\routes.js
create  todo\config\autoload.js
create  todo\db\schema.js
create  todo\public\index.html
create  todo\public\stylesheets\bootstrap.css
create  todo\public\stylesheets\bootstrap-responsive.css
create  todo\public\images\glyphicons-halflings-white.png
create  todo\public\images\glyphicons-halflings.png
create  todo\public\images\compound.png
create  todo\public\javascripts\rails.js
create  todo\public\javascripts\bootstrap.js
create  todo\public\javascripts\application.js
create  todo\public\favicon.ico
create  todo\Procfile
create  todo\README.md
create  todo\package.json
create  todo\server.js
create  todo\.gitignore
create  todo\config\database.js
create  todo\app\views\layouts\application_layout.ejs
create  todo\app\controllers\application_controller.js

C:\Node4Compound>
C:\Node4Compound>cd todo

C:\Node4Compound\todo>dir
 Volume in drive C has no label.
 Volume Serial Number is 5449-2F7F

 Directory of C:\Node4Compound\todo

13-Feb-17  03:24 PM    <DIR>          .
13-Feb-17  03:24 PM    <DIR>          ..
13-Feb-17  03:24 PM               154 .gitignore
13-Feb-17  03:24 PM    <DIR>          app
13-Feb-17  03:24 PM    <DIR>          config
13-Feb-17  03:24 PM    <DIR>          db
13-Feb-17  03:24 PM    <DIR>          log
13-Feb-17  03:24 PM    <DIR>          node_modules
13-Feb-17  03:24 PM               612 package.json
13-Feb-17  03:24 PM                19 Procfile
13-Feb-17  03:24 PM    <DIR>          public
13-Feb-17  03:24 PM                29 README.md
13-Feb-17  03:24 PM               839 server.js
               5 File(s)          1,653 bytes
               8 Dir(s)  182,149,808,128 bytes free

C:\Node4Compound\todo>npm install

Bunch of warnings on pug, graceful and minimatch

    | +-- asynckit@0.4.0
    | `-- combined-stream@1.0.5
    |   `-- delayed-stream@1.0.0
    +-- formidable@1.1.1
    +-- qs@6.3.0
    `-- readable-stream@2.2.2
      `-- isarray@1.0.0

npm WARN todo@0.0.1 No description
npm WARN todo@0.0.1 No repository field.
npm WARN todo@0.0.1 No license field.

C:\Node4Compound\todo>npm install -g pug
C:\Users\User\AppData\Roaming\npm
`-- pug@2.0.0-beta11


C:\Node4Compound\todo>npm install -g graceful
C:\Users\User\AppData\Roaming\npm
`-- graceful@1.0.1


C:\Node4Compound\todo>npm install -g minimatch
C:\Users\User\AppData\Roaming\npm
`-- minimatch@3.0.3

No more warning messages

C:\Node4Compound\todo>npm install
npm WARN todo@0.0.1 No description
npm WARN todo@0.0.1 No repository field.
npm WARN todo@0.0.1 No license field.

C:\Node4Compound\todo>

C:\Node4Compound\todo>node server.coffee
module.js:471
    throw err;
    ^

Error: Cannot find module 'C:\Node4Compound\todo\server.coffee'
    at Function.Module._resolveFilename (module.js:469:15)
    at Function.Module._load (module.js:417:25)
    at Module.runMain (module.js:604:10)
    at run (bootstrap_node.js:394:7)
    at startup (bootstrap_node.js:149:9)
    at bootstrap_node.js:509:3

WORKAROUND

C:\Node4Compound\todo>set DEBUG todo:* & npm start
Environment variable DEBUG todo:*  not defined

> todo@0.0.1 start C:\Node4Compound\todo
> node server.js

express deprecated app.configure: Check app.get('env') in an if statement config
\environment.js:6:9
connect deprecated methodOverride: use method-override npm module instead config
\environment.js:16:25
express deprecated app.configure: Check app.get('env') in an if statement config
\environments\development.js:6:9
(node:7336) DeprecationWarning: sys is deprecated. Use util instead.

Compound server listening on 0.0.0.0:3000 within development environment


Expressjs +Compound : Routing

Explore app structure

Router

Let's start with routes because this is the first place in the compound stack where request handling happens. In other words, when you open http://localhost:3000/lists in your browser, the router should decide what part of the application should handle this request. Routes are configuration rules that explain to the application what paths your application can handle.
Routes are listed in the file config/routes.js which looks like this:
exports.routes = function (map) {
    map.resources('lists');
    map.all(':controller/:action');
    map.all(':controller/:action/:id');
};
The line map.resources('lists'); was added by the list scaffolding generator. The command compound routes will generate a table that shows all the routes that are available to the app.
Note how the line "map.resources('lists');" generates a collection of predefined routes.
     lists GET    /lists.:format?          lists#index
     lists POST   /lists.:format?          lists#create
  new_list GET    /lists/new.:format?      lists#new
 edit_list GET    /lists/:id/edit.:format? lists#edit
      list DELETE /lists/:id.:format?      lists#destroy
      list PUT    /lists/:id.:format?      lists#update
      list GET    /lists/:id.:format?      lists#show
           ALL    /:controller/:action     undefined#undefined
           ALL    /:controller/:action/:id undefined#undefined
In this table the first column shows the route helper name, the second describes the method (aka verb) for the route, the third describes the route itself, and the last column shows the controller#action that handles the request. As you can see, a route is a pattern that defines what a resource request will look like in the address bar of a browser. When a browser asks the server for a route like /lists/1/ the router will test it against these patterns to determine how to handle it.
Note that the word Request has special meaning in Node programming.
It refers to the object created whenever a browser requests the server do anything. To anyone visiting your app in a browser the request is represented by the address in the address bar. To your app the request is represented by the reqobject. That object contains several properties including the address that the browser requested.
To make the process of including routes in pages easier, Compound includes router helpers. The helper name should be used to generate paths, and all route helpers are available as methods on the pathTo object. These next examples show the output of calling the list router helpers:
pathTo.lists() // '/lists'
pathTo.lists({format: 'json'}); // '/lists.json'
pathTo.list(1); // '/lists/1'
pathTo.list(1, {format: 'json'}); // '/lists/1.json'
pathTo.list({id: 1, format: 'json'}); // '/lists/1.json'
pathTo.new_list(); // '/lists/new'
pathTo.edit_list(1); // '/lists/1/edit'
pathTo.edit_list('my-list'); // '/lists/my-list/edit'
By default path helpers are generated with underscores as word separators. This behavior will be changed in future versions and it's highly recommended to add the line map.camelCaseHelperNames = true; to the top of the router file to generate the names in camelCase: newList and editList instead of new_list and edit_list

Expressjs + Compound : Generate scaffolding for Lists

Generate scaffolding for Lists

Run this command:
`compound generate scaffold list name`
It will generate all necessary files for the List model.
if you haven't already done so, stop the server using the CTRL+C hotkey and restart it using node . (or your preferred startup command) so that you can review the changes in your browser.
In development mode every modification of an existing model, controller or view file will be updated automatically, but when you modify routes or schema you have to restart the server manually. Alternatively use the node-dev command (npm install node-dev first) to restart server automatically on every file change.
Now, visit http://localhost:3000/lists to see the new version of your app.
Now that we have some files in our application, it's time to explore the structure. Let's get a brief overview of the files we have to get our new lists CRUD functionality (create-read-update-delete) working.

C:\Node4Express\todo-list>compound generate scaffold list name
express deprecated app.configure: Check app.get('env') in an if statement config
\environment.js:6:9
connect deprecated methodOverride: use method-override npm module instead config
\environment.js:16:25
express deprecated app.configure: Check app.get('env') in an if statement config
\environments\development.js:6:9
exists  app/
exists  app/controllers/
exists  app/helpers/
exists  app/views/
create  app/views/lists/
exists  app/views/layouts
create  test/
create  test/controllers/
create  app/controllers/lists_controller.js
exists  app/
exists  app/models/
create  app/models/list.js
patch   db/schema.js
create  app/views/layouts/lists_layout.ejs
create  app/views/lists/_form.ejs
create  app/views/lists/show.ejs
create  app/views/lists/new.ejs
create  app/views/lists/edit.ejs
create  app/views/lists/index.ejs
create  app/helpers/lists.js
create  test/controllers/lists_controller_test.js
create  test/test_helper.js
patch   config/routes.js

C:\Node4Express\todo-list>