Wednesday, February 7, 2018

Build a Node JS API

To do this API practice I used Express as framework of Node JS, MongoDB as the database, and a package called body-parser to help deal with JSON requests.

You have to create a new folder and cd into it...
Then you have to run
npm init

After that you can see package.json file.

To use Express as framework for Node JS we have to install Express by typing
npm install --save express mongodb@2.2.16 body-parser

Then installing Nodemon as a dev dependency is a best way. Because it’s a simple little package that automatically restarts the server when files change.

npm install --save-dev nodemon

Then we have to add the following in package.json

"scripts": {
"dev": "nodemon server.js"
},

Therefore, the final package.json file will be like this

{
"name": "notable",
"version": "1.0.0",
"description": "",
"main": "server.js",
"scripts": {
"dev": "nodemon server.js"
},
"author": "",
"license": "ISC",
"dependencies": {
"body-parser": "^1.15.2",
"express": "^4.14.0",
"mongodb": "^2.2.16"
},
"devDependencies": {
"nodemon": "^1.11.0"
}
}

Then server.js file should be created. This file is main to run an app.

So, inside the server we have to require our dependency packages ..
Here..

const express = require('express');
const MongoClient = require('mongodb').MongoClient;
const bodyParser = require('body-parser');
const app = express();

MongoClient will interact with database.
Then we have to initialize the app as an instance of Express,  framework.

Afterward we have to define the port number to listen for HTTP requests.

const port = 8000;
app.listen(port, () => {
console.log('We are live on ' + port);
});


Then we have to go to terminal and type  
npm run dev 

Yeah.. we launched our server.. now you can see on localhost:8000 on your browser..

REad more... 

Access Mongo DB through Node JS


We have created Mongo Database through Mongo coding. Even we can access the Mongo DB through Node JS; a Server Side language used in Java Script format.

Node.js can use this module to manipulate MongoDB databases:
var mongo = require('mongodb');

Creating a Database

To create a database in MongoDB, start by creating a MongoClient object, then specify a connection URL with the correct ip address and the name of the database you want to create.

MongoDB will create the database if it does not exist, and make a connection to it.
Example:
Create a database called "mydb":

var MongoClient = require('mongodb').MongoClient;
var url = "mongodb://localhost:27017/mydb";
MongoClient.connect(url, function(err, db) {
if (err) throw err;
console.log("Database created!");
db.close();
});


Save the code above in a file called "demo_create_mongo_db.js" and run the file:
Run "demo_create_mongo_db.js"

node demo_create_mongo_db.js

Which will give you this result:
Database created!


Create a collection called "customers":

var MongoClient = require('mongodb').MongoClient;
var url = "mongodb://localhost:27017/mydb";
MongoClient.connect(url, function(err, db) {
if (err) throw err;
db.createCollection("customers", function(err, res) {
if (err) throw err;
console.log("Collection created!");
db.close();
});
});


Save the code above in a file called "demo_mongodb_createcollection.js" and run the file:

Run "demo_mongodb_createcollection.js"
node demo_mongodb_createcollection.js

Which will give you this result:
Collection created!

Insert a document in the "customers" collection:

var MongoClient = require('mongodb').MongoClient;
var url = "mongodb://localhost:27017/mydb";
MongoClient.connect(url, function(err, db) {
if (err) throw err;
var myobj = { name: "Company Inc", address: "Highway 37" };
db.collection("customers").insertOne(myobj, function(err, res) {
if (err) throw err;
console.log("1 document inserted");
db.close();
});
});


Save the code above in a file called "demo_mongodb_insert.js" and run the file:

Run "demo_mongodb_insert.js"
node demo_mongodb_insert.js

Which will give you this result:

1 document inserted

Insert multiple documents in the "customers" collection:

var MongoClient = require('mongodb').MongoClient;
var url = "mongodb://localhost:27017/mydb";
MongoClient.connect(url, function(err, db) {
if (err) throw err;

var myobj = [
{ name: 'John', address: 'Highway 71'},
{ name: 'Peter', address: 'Lowstreet 4'},
{ name: 'Amy', address: 'Apple st 652'},
{ name: 'Hannah', address: 'Mountain 21'},
{ name: 'Michael', address: 'Valley 345'},
{ name: 'Sandy', address: 'Ocean blvd 2'},
{ name: 'Betty', address: 'Green Grass 1'},
{ name: 'Richard', address: 'Sky st 331'},
{ name: 'Susan', address: 'One way 98'},
{ name: 'Vicky', address: 'Yellow Garden 2'},
{ name: 'Ben', address: 'Park Lane 38'},
{ name: 'William', address: 'Central st 954'},
{ name: 'Chuck', address: 'Main Road 989'},
{ name: 'Viola', address: 'Sideway 1633'}
];

db.collection("customers").insertMany(myobj, function(err, res) {
if (err) throw err;
console.log("Number of documents inserted: " + res.insertedCount);
db.close();
});
});

Save the code above in a file called "demo_mongodb_insert_multiple.js" and run the file:

Run "demo_mongodb_insert_multiple.js"
node demo_mongodb_insert_multiple.js

Which will give you this result:

Number of documents inserted: 14
Find the first document in the customers collection:

var MongoClient = require('mongodb').MongoClient;
var url = "mongodb://localhost:27017/mydb";
MongoClient.connect(url, function(err, db) {
if (err) throw err;
db.collection("customers").findOne({}, function(err, result) {
if (err) throw err;
console.log(result.name);
db.close();
});
});

Save the code above in a file called "demo_mongodb_findone.js" and run the file:

Run "demo_mongodb_findone.js"
node demo_mongodb_findone.js

Which will give you this result:

Company Inc.

Find all documents in the customers collection:

var MongoClient = require('mongodb').MongoClient;
var url = "mongodb://localhost:27017/mydb";
MongoClient.connect(url, function(err, db) {
if (err) throw err;
db.collection("customers").find({}).toArray(function(err, result) {
if (err) throw err;
console.log(result);
db.close();
});
});

Save the code above in a file called "demo_mongodb_find.js" and run the file:

Run "demo_mongodb_find.js"
node demo_mongodb_find.js

Which will give you this result:

[
{ _id: 58fdbf5c0ef8a50b4cdd9a84 , name: 'John', address: 'Highway 71'},
{ _id: 58fdbf5c0ef8a50b4cdd9a85 , name: 'Peter', address: 'Lowstreet 4'},
{ _id: 58fdbf5c0ef8a50b4cdd9a86 , name: 'Amy', address: 'Apple st 652'},
{ _id: 58fdbf5c0ef8a50b4cdd9a87 , name: 'Hannah', address: 'Mountain 21'}
]

Find documents where the address starts with the letter "S":

var MongoClient = require('mongodb').MongoClient;
var url = "mongodb://localhost:27017/mydb";
MongoClient.connect(url, function(err, db) {
if (err) throw err;
var query = { address: /^S/ };
db.collection("customers").find(query).toArray(function(err, result) {
if (err) throw err;
console.log(result);
db.close();
});
});

Save the code above in a file called "demo_mongodb_query_s.js" and run the file:

Run "demo_mongodb_query_s.js"
node demo_mongodb_query_s.js

Which will give you this result:

[
{ _id: 58fdbf5c0ef8a50b4cdd9a8b , name: 'Richard', address: 'Sky st 331' },
{ _id: 58fdbf5c0ef8a50b4cdd9a91 , name: 'Viola', address: 'Sideway 1633' }
]

Manage Packages with NPM - Node Package Manager

Node JS used to write JavaScript on the server side. To install specific packages to do a proper web development; npm is used. We require dependencies in package.json file. Then the node packages will be downloaded.

 To do we have to run npm init to initialize the program.

npm used to . . .
  • Adapt packages to your apps, or incorporate them as they are.
  • Download standalone tools you can use right away.
  • Run packages without downloading using npx.
  • Share code with any npm user, any where.
  • Restrict code to specific developers.
  • Form virtual teams (orgs).
  • Manage multiple versions of code and code dependencies.
  • Update applications easily when underlying code is updated.
  • Discover multiple ways to solve the same puzzle.
  • Find other developers who are working on similar problems.
Using npm init to Initialize a Project The npm init command is a step-by-step tool to scaffold out your project. It will prompt you for input for a few aspects of the project in the following order:
  • The project's name,
  • The project's initial version,
  • The project's description,
  • The project's entry point (meaning the project's main file),
  • The project's test command (to trigger testing with something like Standard)
  • The project's git repository (where the project source can be found)
  • The project's keywords (basically, tags related to the project)
  • The project's license (this defaults to ISC - most open-source Node.js projects are MIT)

A Sample package.json file is

{
"name": "metaverse", // The name of your project
"version": "0.92.12", // The version of your project
"description": "The Metaverse virtual reality. The final outcome of all virtual
worlds, augmented reality, and the Internet.",
// The description of your project

"main": "index.js"
"license": "MIT" // The license of your project
}

package.json file is always structured in the JSON format.

Node JS Exercise

Click here to see original PDF Version of  Questions & Answers..

Create a simple http server and print “Welcome to Uki. I am yourname” when a request is sent to your server via the port 8000. (Note - Change different port numbers and check)


Using the file system module create a new file called ukinode.txt

3.1 Write a paragraph about Uki into that file


3.3 Append another paragraph about Uki and now serve the new file

3.4 Rename the file as ukinodejsexercise1.txt

3.5 Delete the file you created



4. Create two html files called head.html which is a web page which says ‘you have got head ‘ and tail.html which is a web page which says ‘you have got tail’ and save them in the same folder as your node.js files. Create a Node.js file that opens the requested file and returns the content to the client. If anything goes wrong, throw a 404 error.

If you have followed the correct steps you should see two different results when opening these two addresses:

http://localhost:8080/head.html - > You have got head

http://localhost:8080/tail.html -> You have got tail



5. Install the package “upper-case” using NPM and create a Node.js file that will convert the output "Uki is the best place to learn programming !" into upper-case letters.


6. Create an event handler function that will say “I bark when I see strangers !” when a "bark" event is fired.

7. Install “formidable” module using npm and make a web page in Node.js that lets the user upload files to your computer.

7.1 Save that uploaded file into your Documents directory.

8. Using the Nodemailer module create a server and send a mail to info@uki.life with the subject : “Testing my nodemailer module” , text: “This is easy !”

8.1 Now instead of text send a basic html formatted mail.

Thursday, January 4, 2018

Node JS - Day 39


Node.js is open source, completely free, and used by thousands of developers around the world. It is used to develop I/O intensive web applications like video streaming sites, single-page applications, and other web applications.

Features of Node.js
  • Asynchronous and Event Driven
  • Very Fast
  • Single Threaded but Highly Scalable
  • No Buffering 


Where to Use Node.js?

Following are the areas where Node.js is proving itself as a perfect technology partner.
  • I/O bound Applications
  • Data Streaming Applications
  • Data Intensive Real-time Applications (DIRT)
  • JSON APIs based Applications
  • Single Page Applications

Node JS code have the following three important keyword..

Import required modules − We use the require directive to load Node.js modules.

Creating server − A server which will listen to client's requests

Read request and return response − The server created in an earlier step will read the HTTP request made by the client which can be a browser or a console and return the response.

Tuesday, January 2, 2018

Responsive Design - Day 38

It's important for websites to resize and reorganize their content to best fit screens of all sizes. When a website doesn't respond to different screen sizes, the website may look odd or become indecipherable on certain devices.

Media Queries

CSS uses media queries to adapt a website's content to different screen sizes. With media queries, CSS can detect the size of the current screen and apply different CSS styles depending on the width of the screen.

@media only screen and (max-width: 480px) { body { font-size: 12px; } }.

1. @media — This begins a media query rule and instructs the CSS compiler on how to parse the rest of the rule.

2. only screen — Indicates what types of devices should use this rule. In early attempts to target different devices, CSS incorporated different media types (screen, print, handheld). The rationale was that by knowing the media type, the proper CSS rules could be applied. However, “handheld” and “screen” devices began to occupy a much wider range of sizes and having only one CSS rule per media device was not sufficient. screen is the media type always used for displaying content, no matter the type of device. The only keyword is added to indicate that this rule only applies to one media type (screen).

3. and (max-width : 480px) — This part of the rule is called a media feature, and instructs the CSS compiler to apply the CSS styles to devices with a width of 480 pixels or smaller. Media features are the conditions that must be met in order to render the CSS within a media query.

CSS rules are nested inside of the media query's curly braces. The rules will be applied when the media query is met. In the example above, the text in the body element is set to a font-size of 12px when the user's screen is less than 480px.

Responsive Design - Day 37

Responsive design! Responsive design refers to the ability of a website to resize and reorganize its content based on:
  1. The size of other content on the website.
  2. The size of the screen the website is being viewed on.
Em
Incorporating relative sizing starts by using units other than pixels. One unit of measurement you can use in CSS to create relatively-sized content is the em, written as em in CSS.

.p { font-size: 2em; }

Here, no base font has been specified, therefore the font size of the paragraph element will be set relative to the default font size of the browser. Assuming the default font size is 16 pixels, then the font size of the heading element will be 32 pixels.

Rem
Rem stands for root em. It acts similar to em, but instead of checking parent elements to size font, it checks the root element. The root element is the <html> tag.

html { font-size: 20px; }
h1 { font-size: 2rem; }

Here, font-size of  whole html tag to 20px. So, font-size of Heading will be 40px.
One advantage of using rems is that all elements are compared to the same font size value, making it easy to predict how large or small font will appear.