Node.js -3 | Reading user input from the command line

Readline module, which comes with the Node.js core reads user input so that you can use it as an interaction.

In this example, the user will tell how many glasses of water he/she drinks each day and we’ll say if it’s healthy enough or not.

In the script.js file, require the module like:

var rl = require("readline");

Create the prompts variable:

var prompts = rl.createInterface(process.stdin, process.stdout);

Request user input with a question:

prompts.question("How many glass of water do you drink each day?", function (glasses) {
	var message = "";
	if (glasses > 5) {
		message = "Great! Water is the key of a healthy life.";
	} else {
		message = "Are you drinking just " + glasses + " glass of water? You should drink at least " + (6 - glasses) + " more.";
	}
	console.log(message);
	process.exit();
});

Output will be like:

> node script.js
> How many glass of water do you drink each day?
> 5
> Are you drinking just 5 glass of water? You should drink at least 1 more.
> node script.js
> How many glass of water do you drink each day?
> 7
> Great! Water is the key of a healthy life.
Post a comment

Node.js -2 | Modules: Custom Module and Sample Usage of Markdown Module

In this post, I’ll share some code about how to use modules in Node.js. I will use a custom module (user-defined) and a public module (Markdown module). The code samples are form Lynda.com’s Node.js lessons.

——

Defining a local module (A module that returns Fibonacci numbers)

1- In the root of Node.js application, navigate to node_modules folder and then create a dir for your module:

> cd node_modules
> mkdir data_module

2- Create module file:

> nano fibonacci.js

And edit its content like this:

exports.data = [1,1,2,3,4,8,13,21];

Save and exit the editor.

3- In app root folder, create the main file:

> cd ..
> nano script.js

And edit like this:

// './' prefix tells that the module is local, not global
var sequence = require("./fibonacci");
console.log(sequence.data);

Note: “Local modules are useful for when you want to separate your data from your code.”

——

Markdown module simple usage

First, create a Node.js app with Markdown module dependency enabled and install these dependencies as I talked about here.

In your script.js file:

var parser = require("node-markdown");
var html = parser.Markdown("This is a **markdown** text.");
console.log(html);
Post a comment

Node.js -1 | Initialize a Node.js project with dependencies

Not so long ago I’ve started to study lessons about Node.js. There’s no need to praise or to talk about it or why I want to learn it, it just excites me as a new platform and I intend to keep studying unless I don’t feel like it’s not worth it -which I doubt.

Here I want to share my Node.js notes regularly, from very basic to the complex(hopefully).

———

Running Node.js scripts

Download and install from:

http://nodejs.org/

To build (run) a Node.js script:

> node file.js

———

Initializing a node app and build it with dependencies

1- Initialize:

> npm init

2- After initialization, package.json contains project information. You can add “dependencies” to this file like:

"dependencies": {
	"node-markdown": "0.1.0"
}

If you want to require latest version of a dependency module:

"node-markdown": "*"

3- Install these dependencies:

> npm install

———

Some other useful stuff about managing the app

Update these dependencies to latest versions:

> npm update

Update node.js global libraries:

> npm update -g

Remove an installed library:

# remove from "dependencies" object in package.json, then:
> npm prune

Search through node.js modules available for free:

> npm search 
# better not to use it without grep or it may take quite long time
> npm search | grep markdown
# or find from http://npmjs.org

Tail changes of a file and execute it automatically on console after each change:

# -g installs as global
> sudo npm install node-dev -g
> node-dev script.js

———

No “Hello, world!” yet. These are just basics that we’ll probably do quite seldom.

Post a comment

Selecting Grouped Row Count When Using MySQL GROUP BY Column

You may have been using subqueries to get how many rows were grouped when using MySQL’s GROUP BY function. There’s a little trick that helps to get this number without using subqueries, more clean and faster (when the amount of rows get higher).

Let’s assume we have a table contain folks from different cities. Like this:

folk_name   |   city_name
---------------------------
evren       |   ohio
steve       |   ohio
cem         |   weston
don         |   sunderland
ritchie     |   weston
ian         |   hounslow
alican      |   ohio

When we want to get only city names (distinct) from this table, we may group the data by city_name column like this:

SELECT f.* FROM `folks` f GROUP BY f.`city_name`

And the result would be:

folk_name   |   city_name
---------------------------
ian         |   hounslow
evren       |   ohio
don         |   sunderland
cem         |   weston

The expected behaviour of GROUP BY is to select first rows so other folks from same cities do not appear. It also orders by the GROUP BY column (ascending).

Let’s say we want to get how many folks exist in each city by grouping by. First thing comes to mind could be using a subquery like this:

SELECT f1.*, (SELECT COUNT(f2.`folk_name`) FROM `folks` f2 WHERE f2.`city_name` = f1.`city_name`) AS `folk_count` FROM `folks` f1 GROUP BY `city_name`

And the result would be:

folk_name   |   city_name   |   folk_count
-------------------------------------------
ian         |   hounslow    |   1
evren       |   ohio        |   3
don         |   sunderland  |   1
cem         |   weston      |   2

Let’s admit, subqueries are messy. They make the query more complicated to read and also are question marks on performance.

How about selecting number 1 (one) for each row and sum it up on grouping by?

Doing something like this:

SELECT f.*,SUM(1) AS `folk_count` FROM `folks` f GROUP BY f.`city_name`

Would return:

folk_name   |   city_name   |   folk_count
-------------------------------------------
ian         |   hounslow    |   1
evren       |   ohio        |   3
don         |   sunderland  |   1
cem         |   weston      |   2

Nicely done.

Post a comment

DateTime Ticks With Objective-C

If you need to generate unique strings for every case, the concept of DateTime.Ticks is probably the best solution for you. It represents the count of seconds since the oldest DateTime object available.

However, DateTime.Ticks usage comes from .NET platform and it is that easy in .NET, not in Objective-C.

To generate a ticks number in Objective-C, you need to do the following:

  1. Create an NSDate (01.01.0001), I know, rocking.
  2. Calculate the ticks between this oldest date and [NSDate date] (which means now).
  3. Turn that double variable to an integer. Well, long integer. Or… long long integer. (True story).

Here’s how I did it:

// Create the date formatter
NSDateFormatter *dateFormat = [[NSDateFormatter alloc] init];
[dateFormat setDateFormat:@"yyyyMMdd"];

// Create the oldest day possible
NSDate *ticksDate = [dateFormat dateFromString:@"00010101"];

// Get ticks difference between now and 01.01.0001 in double    
double ticksDouble = [[NSDate date] timeIntervalSinceDate:ticksDate];

// Turn it to a long long int
long long int ticks = llround(ticksDouble);

// Test it
NSLog(@"%lli",ticks);
Post a comment

How to Install Git 1.8.x || Upgrade Git to 1.8.x

hins2

You don’t get surprised when you see that your CentOS, Ubuntu or another server already has Git installed. However, the default Git version that comes with the OS bundle is usually v1.7.1 and this might be a problem when you want to install applications which require higher Git versions(For example, Gitlab).

This article contains the steps that I followed while installing(or upgrading to) Git 1.8.3.4 to a CentOS 6.4 server.

First of all, make sure if you have git installed:

which git

This has to return a value like “/usr/local/bin/git”. If it doesn’t, than you don’t have Git installed on your machine.

If it does return a path, than you better know which version, by using this command:

git --version

The result should be like: “git version 1.7.1”. If it returns the number equals or higher than the version you want to install, well, you got lucky. The day is over for you.

OK, let’s begin with a new installation.

1. Go to /tmp folder:

cd /tmp

(Those who have older version of Git installed may go to step 3.)

2. Install default version of Git and maker for installing git:

yum -y install git perl-ExtUtils-MakeMaker

3. Clone git repo to your /tmp folder:

git clone git://github.com/git/git.git

4. Get inside of the repo and checkout your favorite version. I chose v1.8.3.4, you may choose something else.

cd /tmp/git/
git checkout v1.8.3.4

5. Continue preparing installation:

autoconf
./configure --prefix=/usr/local

IMPORTANT: You might have got an error like “-bash: ./configure: Permission denied”. If you haven’t, continue with step 7. If you have, no need to worry, we’ll fix it by using these commands:
6. Fix “Permission denied” error if exist

mount -o remount,exec,suid /tmp
mount -o remount,exec,suid /var/tmp

7. Do it

make && make install

8. Cleanup

rm -rf /tmp/git/

9. Verify your installation:

which git

(Should return Git path like “/usr/local/bin/git”)

10. Verify your version

git --version

(Should return your version, like: “git version 1.8.3.4”)

You may find most of the steps above in various websites, however it really took me a while to find out how to fix the permission error which I declared in step 6.

Fair enough, let’s go make some fork!

Post a comment