resources

https://nodesource.com/blog/the-basics-getting-started-with-npmthe-basics-getting-started-with-npm

Node.JS commandline options

Is a program that can run Javascript codes. it Has a command-line tool that to run JavaScript programs; they are usualy used as regular web server . Node.js has lot of libraries called pacckages that can be browsed here : npmjs.com`

NVM

Is node version manager to this version the default one: $ nvm alias default 0.10.31

NPM

Is the package manager for javascript and the Node.js server platform. It is included in nodejs installation by default.

Features

- Installs dependencies Locally: It installs application dependencies locally, in a folder inside the project folder, not globally. - multiple versions of the same dependency: It handles multiple versions of the same module at the same time. - tarball or git dependencies: can specify tarballs or git repositories as dependencies. - Easy module publishing (to the npm registry). - Easy creation of CLI utilities that others can install .

Install From source

code:`wget http://nodejs.org/dist/node-v0.4.4.tar.gz $ tar -xzf node-v0.4.4.tar.gz $ cd node-v0.4.4 $ ./configure $ sudo make install`,parent:blk1}); BlockFrame.Block({title:"switching between node versions", code:`$ nvm install v0.8.10 $ nvm use v0.8.10`,parent:blk1}); BlockFrame.Block({title:"list of current ,default and all versions", code:"nvm list"}); BlockFrame.Block({title:"getting the version",code:`node -v`}); BlockFrame.Block({title:"using node commands", body:`1. with no arguments. This will open an interactive shell where you can execute raw JavaScript code.`, code:`$ node > console.log('Hello World'); Hello World`, body2: `2. by providing it a JavaScript file to execute. This is almost always how you will be using it.`, code2: `hello.js console.log('Hello World'); $ node hello.js Hello World`}); //-------------------------------------------------------------------------- BlockFrame.BlockGroup("Learn by step by step example"); BlockFrame.Block({title:`Hello,World! Example of console scripts`, body:`1. create a file named a.js 2. write this line inside it and save: console.log("Hello World"); 3. in command prompt run this command : node h.js 4. finished! It will prints Hello world.`}); BlockFrame.Block({title:"script arguments", body:`1. put this content inside your script

process.argv.forEach((val, index) => {
	console.log('$\{index}: $\{val}');
});
2. run your script by proving arguments:`,code:`node h.js one two=three four`}); BlockFrame.Block({title:"A hello world http server", body:`program responds to hello world via http. We'll call the file 'hello_http.js' and put the following code into it:` ,code:`var http = require('http'); var server = http.createServer( function(req, res) { res.writeHead(200); res.end('Hello Http'); }); server.listen(8080);`, body2:`Now lets run this program from the terminal by typing:`,code2:"$ node hello_http.js", body3:`Testing the server is as simple as opening a new browser tab and navigating to the following url: http://localhost:8080/. you should see : 'Hello Http'. Alternatively, you could also open up a new terminal and use curl to test your server:`, code3:`$ curl localhost:8080 Hello Http`}); BlockFrame.Block({title:"Initialize Project by package.json", body:`Navigate to the directory in which you want your project to exist:`, code:"cd sites/node-test", body2:`Now initalize a new project with npm.`, code2:"npm init", body3: `utility will walk you through creating A package.json file. A package.json is a file that contains metadata about the project, and handles the dependencies (additional software and modules) of the project First, it will ask for a package name: ( The rest you can just press enter and skip. Now you’ll notice we have a package.json file that contains all the information we entered. )`, code3:"node-test"}); BlockFrame.Block({title:"test web projects", body:`try npm start from testsite directory. look at the package.json scripts : { start : node bin/www } So you must execute the www under the bin directory. So instead of node app.js use node bin/www`}); //------------------------------------------------------- BlockFrame.BlockGroup("Modules"); BlockFrame.Block({title:"Modules (or packages or libraries)", body:` The module system allows you to organize your code, hide information and only expose the public interface of a component using module.exports. Every time you use the require call, you are loading another module. Node implements the CommonJS interface for modules. The simplest example can be the following using CommonJS: `, code: `// add.js function add (a, b) { return a + b } module.exports = add //------------------------------------------------------------- //To use the add module we have just created, we have to require it. // index.js const add = require('./add') console.log(add(4, 5)) //------------------------------------------------------------- Under the hood, add.js is wrapped by Node.js this way: (function (exports, require, module, __filename, __dirname) { function add (a, b) { return a + b } module.exports = add }) //------------------------------------------------------------- This is why you can access the global-like variables like require and module. It also ensures that your variables are scoped to your module rather than the global object. `}); BlockFrame.Block({title:"Installing modules from npm", body:`either search for them on the website or on Github. The syntax for installing an npm module locally (where 'express' is module name):`, code:`$ npm install express`, body2:`To add dependency to packages.json use --save:`, code2:"npm install left-pad --save", body3:`You can require module install from npm as you would do with the native ones,no need to specify path:`, code3:"var express = require('express');"}); BlockFrame.Block({title:"Loading depencies(using the require keyword)", body:`Example:`, code:`//we can require some native modules var http = require('http'); var dns = require('dns'); //We can also require relative files: var myFile = require('./myFile'); // loads myFile.js`}); BlockFrame.Block({title:"Another Example in the terminal", body:`Create a index.js file in the root folder of your project and add the code to it:`, code:`//index.js const leftPad = require('left-pad'); // Require left pad const output = leftPad('Hello, World!', 15); // Define output // Send output to the console console.log(output);` ,body2:`Now you can run the project in terminal:` ,code2:`node index.js`}); BlockFrame.Block({title:"Module scope", body:`-Node modules aren't automatically injected into the global scope , instead you just assigned them to a variable of your choice. That means that you don't have to care about two or more modules that have functions with the same name.`}); //------------------------------------------------------------- BlockFrame.BlockGroup("Creating your own modules"); BlockFrame.Block({title:"Step 1: Init authur", code:`configure npm npm set init.author.name "Brent Ertz" npm set init.author.email "brent.ertz@gmail.com" npm set init.author.url "http://brentertz.com" npm adduser`}); BlockFrame.Block({title:"Step 2: required modules", body: `The primary 2 items that we are concerned with here are require and exports. You require other modules that you wish to use in your code and your module exports anything that should be exposed publicly. For example:`, code:`var other = require('other_module'); module.exports = function() { console.log(other.doSomething()); }`}); BlockFrame.Block({title:"Step 3: Creating package.json", body:`Executing the following command will ask you a bunch of questions, and then write out a package.json file.`, code:`npm init`}); BlockFrame.Block({title:"Step 4: primary module ocde", body:`Create an index.js file to hold the primary module code. for example:`, code:`/** * Escape special characters in the given string of html. * * @param {String} html * @return {String} */ module.exports = { escape: function(html) { return String(html) .replace(/&/g, '&') .replace(/"/g, '"') .replace(/'/g, ''') .replace(//g, '>'); }, /** * Unescape special characters in * the given string of html. * @param {String} html * @return {String} */ unescape: function(html) { return String(html) .replace(/&/g, '&') .replace(/"/g, '"') .replace(/'/g, \'\'\') .replace(/</g, '<') .replace(/>/g, '>'); } }; ....`}); //----------------------------------------------- var blkOther=BlockFrame.BlockGroup("Other concepts"); BlockFrame.Block({title:"CallBack", body:`-you are telling it to do something and when it is done it will call your function(callback). -In asynchronous programming we do not return values when our functions are done,but instead we use the continuation-passing style (CPS) Continuation Passing Style (CPS for short) is a style of programming in which functions do not return values; rather, they pass control onto a continuation, which specifies what happens next. `, code: `//Direct style: function direct(x){ return x*x; } //CPS (unnecessary because code is not asynchronous, example only): function cps(x,done){ done(x*x); //call done instead of returning. }`}); BlockFrame.Block({title:`Streams`, body:`represent an abstract interface for asynchronously manipulating a continuous flow of data. They can be classified into 5 types: readable, writable, transform, duplex and classic.` }); BlockFrame.Block({title:"file operations", body:`readFile : takes a file path and a callback. The callback will be invoked when the file is done being read. The file data comes in the form of a Buffer, which is basically a byte array. We can convert it to a string using the toString() function.` ,code:`// Load the fs (filesystem) module. var fs = require('fs');// // Read the contents of the file into memory. fs.readFile('example_log.txt', function (err, logData) { // If an error occurred, throwing it will // display the exception and kill our app. if (err) throw err; // logData is a Buffer, convert to string. var text = logData.toString(); var results = {}; // Break up the file into lines. var lines = text.split('\\n'); lines.forEach(function(line) { var parts = line.split(' '); var letter = parts[1]; var count = parseInt(parts[2]); if(!results[letter]) { results[letter] = 0; } results[letter] += parseInt(count); }); console.log(results); // { A: 2, B: 14, C: 6 } });`}); BlockFrame.Block( {title:`blocking vs non-blocking software development`, body:`Blocking methods execute synchronously and non-blocking methods execute asynchronously`}); BlockFrame.Block({title:`Node Event Loop`, body:`Node.js programs usually use a loop,to check for requests. Node provides the event loop as part of the language The minute that you call Node you don’t have to call a start function to start a loop that’s waiting for events. You literally just put in your script and the loop starts the minute that you start Node and it doesn’t end until the last callback is called `}); BlockFrame.Block({title:"Creating a realtime application with Express and Socket.io" ,body:`Express is the most popular web framework for Node, while Socket.IO is a realtime framework that enables bi-directional communication between web clients and the server. We are going to create a basic tracking pixel application using the two that has a dashboard which reports realtime visits. Besides Express and Socket.IO we will need to install the emptygif module. When the user visits http://localhost:1337/tpx.gif, a message will be sent to all the users that are viewing the homepage. The message will contain information related to the clients, mainly their IP address and user agent. Below is the code for the server.js file: `, code:`var emptygif = require('emptygif'); var express = require('express'); var app = express(); var server = require('http').createServer(app); var io = require('socket.io')(server); app.get('/tpx.gif', function(req, res, next) { io.emit('visit', { ip: req.ip, ua: req.headers['user-agent'] }); emptygif.sendEmptyGif(req, res, { 'Content-Type': 'image/gif', 'Content-Length': emptygif.emptyGifBufferLength, 'Cache-Control': 'public, max-age=0' //or specify expiry to make sure it will call // everytime }); }); app.use(express.static(__dirname + '/public')); server.listen(1337);`}); BlockFrame.Block({title:"The frontend", code:`<!DOCTYPE HTML> <html lang="en"> <head> <meta charset="UTF-8"> <title>Realtime pixel tracking dashboard</title> <style type="text/css"> .visit { margin: 5px 0; border-bottom: 1px dotted #CCC; padding: 5px 0; } .ip { margin: 0 10px; border-left: 1px dotted #CCC; border-right: 1px dotted #CCC; padding: 0 5px; } </style> </head> <body> <h1>Realtime pixel tracking dashboard</h1> <div class="visits"></div> <script src="https://code.jquery.com/jquery-1.10.2.min.js"></script> <script src="//cdnjs.cloudflare.com/ajax/libs/moment.js/2.8.1/moment.min.js"></script> <script src="/socket.io/socket.io.js"></script> <script> $(function() { var socket = io(); var containerEl = $('.visits'); socket.on('visit', function(visit) { var newItem = '<div class="visit">'; newItem += '<span class="date">' + moment().format('MMMM Do YYYY, HH:mm:ss') + '</span>'; newItem += '<span class="ip">' + visit.ip + '</span>'; newItem += '<span class="ua">' + visit.ua + '</span></div>'; containerEl.append(newItem); }); }); </script> </body> </html>`});

BlockFrame.Block({title:"Resources", body:`Main reference source code repository of npmjs on youtube nod.js by gamma beginners guide tutorial with examples building a real time markdown-viewer` });