Thursday 10 August 2017

node Js Notes - Beginner


1. == performs automatic typecasting whereas === does not.
'a' === new String('a') //false
'a' === new String('a').toString() //true

or

'a' == new String('a') //true
0 == false   // true
0 === false  // false, because they are of a different type
1 == "1"     // true, automatic type conversion for value only
1 === "1"    // false, because they are of a different type
null == undefined // true
null === undefined // false
'0' == false // true
'0' === false // false


2.functions are objects:

var obj = function () {
this.color: "green",
this.type: "suv",
this.owner: {
...
}
}

3.A function with a property (remember, functions are just objects that can be invoked/initialized)

var f = function () {console.log('Boo');}
f.boo = 1;
f(); //outputs Boo
console.log(f.boo); //outputs 1

Note - The return keyword is optional. When it is omitted, the function returns undefined on invocation.

4. Pass Functions as Parameters

var convertNum = function (num) {
return num + 10;
}

var processNum = function (num, fn) {
return fn(num);
}

processNum(10, convertNum);



5. functional inheritance pattern

var user = function (ops) {
return { firstName: ops.name || 'John'
, lastName: ops.name || 'Doe'
, email: ops.email || 'test@test.com'
, name: function() { return this.firstName + this.lastName}
}
}
 
var agency = function(ops) {
ops = ops || {}
var agency = user(ops)
agency.customers = ops.customers || 0
agency.isAgency = true
return agency
}


6. Node.js Process Information

$ps aux | grep 'node';
$node -e "console.log(process.pid)")


7. Exporting and Importing Modules

var messages = {
find: function(req, res, next) {
...
},
add: function(req, res, next) {
...
},
format: 'title | date | author'
}
exports.messages = messages;


------------
file that includes the previous sample module:

var app = express();
var config = require('./config/index.js');
app = config(app);



8. path.join() will produce a path with valid slashes (forward or backward depending on your OS).
If require() points to a folder, Node.js attempts to read the index.js file in that folder.

 9. __dirname and process.cwd

__dirname is an absolute path to the file in which the global variable is called, whereas process.cwd is an absolute
path to the process that runs the script. The latter might not be the same as the former if we started the program from
a different folder, such as $ node ./code/program.js.


10. Browser Application Programming Interface Helpers
  
Array
•     some() and every(): assertions for array items
•     join() and concat(): convertion to a string
•     pop(), push(), shift(), and unshift(): working with stacks and queues
•     map(): model mapping for array items
•     filter(): querying array items
•     sort(): ordering items
•     reduce(), reduceRight(): computing
•     slice(): copying
•     splice(): removing
•     indexOf(): lookups of finding the value in the array
•     reverse(): reversing the order
•     The in operator: iteration over array items
Math
•     random()

•    random(): random real number less than one
String
•     substr() and substring(): extracting substrings
•     length: length of the string
•     indexOf(): index of finding the value in the string
•     split(): converting the string to an array
In addition, we have setInterval(), setTimeout(), forEach(), and console methods in Node.js.

11. Node.js Core Modules

•     http (http://nodejs.org/api/http.html#http_http)
•     util (http://nodejs.org/api/util.html)
•     querystring (http://nodejs.org/api/querystring.html)
•     url (http://nodejs.org/api/url.html)
•     fs (http://nodejs.org/api/fs.html)

http:
http.createServer(): returns a new web server object
•     http.listen(): begins accepting connections on the specified port and hostname
•     http.createClient(): is a client and makes requests to other servers
•     http.ServerRequest(): passes incoming requests to request handlers
•   
•     data: emitted when a part of the message body is received
•     end: emitted exactly once for each request
•     request.method(): the request method as a string
•     request.url(): request URL string
http.ServerResponse(): creates this object internally by an HTTP server — not by
the user— and is used as an output of request handlers
•     response.writeHead(): sends a response header to the request
•     response.write(): sends a response body
•     response.end(): sends and ends a response body

util

•    util.inspect(): returns a string representation of an object, which is useful for debugging

querystring

•     querystring.stringify(): serializes an object to a query string
•     querystring.parse(): deserializes a query string to an object

url

parse(): takes a URL string and returns an object

fs

•     fs.readFile(): reads files asynchronously
•     fs.writeFile(): writes data to files asynchronously

12. Reading to and Writing from the File System in Node.js

var fs = require('fs');
var path = require('path');
fs.readFile(path.join(__dirname, '/data/customers.csv'), {encoding: 'utf-8'}, function (err, data) {
if (err) throw err;
console.log(data);
});

To write to the file, execute the following:

var fs = require('fs');
fs.writeFile('message.txt', 'Hello World!', function (err) {
if (err) throw err;
console.log('Writing is done.');
});

13. Streaming Data in Node.js

fs.createReadStream('./data/customers.csv').pipe(process.stdout);
we need either the package.json file or the node_modules
folder to install modules locally with $ npm install name
we need either the package.json file or the node_modules
folder to install modules locally with $ npm install name

For example, $ npm install superagent; in the program.
var superagent = require('superagent');.

14. best practice is not to include a node_modules folder in the Git repository when the project is a module that
is supposed to be used in other applications. However, it’s recommended to include node_modules for deployable
applications to prevent breakage caused by unfortunate dependency updates.

15. Taming Callbacks in Node.js
fs.readdir(source, function(err, files) {
if (err) {
console.log('Error finding files: ' + err)
} else {
files.forEach(function(filename, fileIndex) {
console.log(filename)
gm(source + filename).size(function(err, values) {
if (err) {
console.log('Error identifying file size: ' + err)
} else {
console.log(filename + ' : ' + values)
aspect = (values.width / values.height)
widths.forEach(function(width, widthIndex) {
height = Math.round(width / aspect)
console.log('resizing ' + filename + 'to ' + height + 'x' + height)
this.resize(width, height).write(destination + 'w' + width + '_' + filename, function(err) {
if (err) console.log('Error writing file: ' + err)
})
}.bind(this))
}
})
})
}
});


16. Hello World Server with HTTP Node.js Module

var http = require('http');
var fs = require('fs');

var server = http.createServer(function(request, response) {
    console.log('Request from :'+request.url );
    response.writeHead('200', {'Content-Type':'text/plain'});
    response.end('Hello World\n');
   
});

server.listen('3001', 'localhost');
console.log('server started at localhost:3001');

17. Debugging Node.js Programs
server.js

Core Node.js Debugger
Run  below as $ node debug server.js

var http = require('http');
var fs = require('fs');

var server = http.createServer(function(request, response) {
    console.log('Request from :'+request.url );
    response.writeHead('200', {'Content-Type':'text/plain'});
    debugger; //add this  to debug statements
    response.end('Hello World\n');
   
});

server.listen('3001', 'localhost');
console.log('server started at localhost:3001');


The main node debug commands are as follows:
•     next, n: step to the next statement
•     cont, c: continue until the next debugger/break point
•     step, s: step inside the function call
•     out, o: step outside the function call
•     watch(expression): watch the expression

 Debugging with Node Inspector -
$npm install -g node-inspector
$ node-inspector   -- this start node inspector
start the program in a new terminal window/tab/session with --debug or --debug-brk flags (not just debug)
 For example:

$ node --debug-brk server.js
or
$ node --debug server.js

18. Watching for File Changes

nodemon is a good module for capturing js file changes. no need to restart the node.

$ npm install -g node-dev

use $nodemon <filename.js>

Other modules for files watching:

•     forever -usually used in production (we examine this topic in Chapter 11)
•     node-dev
•     supervisor
•     up - now a deprecated module

No comments:

Post a Comment

Extract error records while inserting into db table using JDBCIO apache beam in java

 I was inserting data into postgres db using apache beam pipeline. it works perfectly with JdbcIO write of apache beam library. But, now, i ...