Fast and painless installation of nodejs and npm

Nodejs community usually uses npm (simple package manager for nodejs) to distribute their projects. In other words, you should have npm installed on your dev/prod machine to move fast in deployment phase.

Although both nodejs and npm installations are really easy, installing npm toke too much time of me. It didn’t work when I followed the instructions on github page.

Anyway, I’ve solved the problem by following the instructions (actually just a copy-paste) in the following link: http://gist.github.com/579814

This link is also given on github page of npm.

It basically installs the latest version of nodejs and after that npm.

You can enjoy “npm install” commands, now…

Posted in sips | Leave a comment

node.js and Session Handling

node.js provides you a very fast HTTP server, however you have to implement many features by yourself, or you can try to find modules/projects developed for node.js. I prefer the first way and actually this the most fun part of it.

Session handling requires that you start a session on server side. Depending on if you know that the request is from a new source or the same source, you should either start a new session or resume an old session. To understand if you are dealing with the same source, in the HTTP world, cookies is the best solution. (You can also use URLs instead of cookies but for practical reasons you would like focus on clients that support cookies)

What we do is to store a unique session key (Session ID or SID) in the cookie. That way, each time a request from the source hits your server you will get a SID which you can compare in your list of session ids to find the session linked to source.

I’ve implemented a session logic the code of which can be found below. The code is not reusable alone, because it depends on a simple framework that I’m working on, but the code can give insight about how session handling could be implemented.

Although the current implementation is an object hash in memory where keys are the SIDs and the values are objects that keep the session related data, I’ve kept a callback parameter to support async calls in the future. (Probably I’ll use something like memcached next time to keep session information)

The logic is as follows:
- If the request has a cookie with the name ‘SESSIONID’ try to find the session information. If there is no session information or session is timed out, start a new session immediately.
- Add the new/old session id to the cookie of the response.
- set/get methods are used to change or access values stored in sessions. Probably, an authentication system may use these functions to store login information of a user. As you can realize, they are also async function expecting a callback from the caller.

I’ll write later on the cookie logic. In the meantime, I may also improve session logic with the support of memcache.

var sessions = {};

var SID_STRING = 'SESSIONID';
var TIMEOUT = 3*60*1000;

exports.start = function(req, res, callback) {
	var setSid = function(sid) {
		sessions[sid]['__timeout'] = Date.now() + TIMEOUT;
		req.cookies[SID_STRING] = sid;
		gj.cookie.set(res,SID_STRING,sid);
		callback.apply(undefined,[null]);
	}

	if(req.cookies[SID_STRING] != undefined) {
		sid = req.cookies[SID_STRING];
	} else {
		createNew(req, setSid);
		return;
	}

	if(sessions[sid] == undefined) {
		createNew(req, setSid);
	} else if(sessions[sid]['__timeout'] < Date.now()) {
		delete sessions[sid];
		createNew(req, setSid);
	} else {
		setSid(sid);
	}

}

var createNew = function(req, callback) {
	sid = gj.util.md5.hash(req.socket.remoteAddress + "" + Date.now());
	sessions[sid] = {__timeout:Date.now() + TIMEOUT};
	callback.apply(undefined,[sid]);
}

exports.end = function(req, res) {
	delete sessions[res.cookies[SID_STRING]];
	gj.cookie.unset(res,SID_STRING);
}

exports.set = function(req, key, value, callback) {
	if(req.cookies == undefined || req.cookies[SID_STRING] == undefined) {
		callback.apply(undefined,["No session defined"]);
	}
	var sid = req.cookies[SID_STRING];
	var session_object = sessions[sid];
	if(session_object) {
		session_object[key] = value;
		callback.apply(undefined,[null]);
	} else {
		callback.apply(undefined,["Can't set session value"]);
	}
}

exports.get = function(req, key, callback) {
	if(req.cookies == undefined || req.cookies[SID_STRING] == undefined) {
		callback.apply(undefined,[null]);
	}
	var sid = req.cookies[SID_STRING];
	var session_object = sessions[sid];
	if(session_object) {
		callback.apply(undefined, [session_object[key]]);
	} else {
		callback.apply(undefined, [null]);
	}
}
Posted in nodejs, sips | Tagged , , | 2 Comments

Inception is a good movie…

…if the whole movie is just a dream.

The movie is like a dream: the story has so many holes, jumps from scenes to scenes are so random and without solid reasons, and the characters are so weak and shallow. These is exactly what happens in our dreams. If this is the case, if all of that were intentional in the movie, then, I really like the movie.

If you have watched the movie EXistenZ, you may remember how the characters were acting like in a high school drama. However, in the course of the movie, you understand the reason of this bad acting and bad script; it’s because of that everything was a game.

That is said, the answer of the question if the spin top stopped or not depends on if the movie was good or bad. For me, it shouldn’t stop if it is a good movie.

Posted in sips | Tagged , | 1 Comment

Earthlings…

I’ve watched the documentary “Earthlings“. It displays very shocking facts (by shocking I mean if you were unaware) about how we treat animals. There are so many torture and misbehaviour in the lifetime of any animal that feeds, entertains, or accompany us. Although the facts summarized are from old video shootages I believe most of them are still true.

Unfortunately, the documentary is too weak in suggesting solutions. It only tries to show the facts in an intentionally disturbing way. You really get shocked. But, that’s it.

In today’s minds such documentaries are just boring. People cannot be inspired by repeated statements and facts about how bad or stupid they are. They already say it to themselves. They are more eager to hear solutions and I believe people who prepared the documentary Earthlings could have done a better job.

I remember a very good example of such a documentary: Home.

Posted in sips | Leave a comment

Writing a set of helper functions classes for node.js

I’ve started a new project on github to implement some functionality on nodejs that makes web development easy and fun. I’ve started with the handler class which maps given url patterns to functions or node modules. You can get the code from http://github.com/ctulek/nodul. The next step will be to implement autoloading of modules. That is, when you change the code of your module it will reload it.

Posted in nodejs, sips | Leave a comment

Garage Sales at Weekends


One thing that I really liked here is garage sales. At weekends, when you go for a morning walk you can always find a garage sale in the neighbourhood. People sell such interesting stuff that you cannot find them in any store all at the sametime.

My wife and I usually buy books. For $10 you can buy 10 books, most of them being hardcover. To be honest, I have not made a visit to Amazon, yet.

Posted in sips | Leave a comment

Handling Time Zones in PHP

Some problems have many solutions which makes them boring to work on. Saving and displaying the date time information in the correct timezone is such a problem. You can use existing libraries, you can have your own solution or you can mix all of them together. Using libraries requires reading documentations, your own solution requires more coding, and mixing them requires both reading and coding. At the end of the day, you just want to find a simple example that shows how easy it is. I’ve found it after reading documentations, trying my own solution and mixing all of them. I just write this long introduction, so that you spend sometime by reading to deserve getting the solution, at least.

Example:

You have a $time string with the west cost time zone  and want to get the time for the east cost.

$dt = new DateTime($time, new DateTimeZone(“America/Los_Angeles”));
$dt->setTimezone(new DateTimeZone(“America/New_York”));
$dt->format(“M d, Y – h:i A T”);

That’s it.

In addition, DateTime and DateTimeZone classes handle daylight saving time changes, too. This is very handy because different countries use different calendar days for daylight saving switches. It is actually just because of that, that you give the location of timezone to DateTimeZone class instead of a number.

List of timezones: http://www.kevinbradwick.co.uk/2010/01/accessing-a-timezone-list-in-php/

Setting your timezone: date_default_timezone_set(“America/Los_Angeles”);

Posted in php | Tagged , | Leave a comment

After meeting with people from nodeJS community…

Yesterday, I had a chance to meet people from nodeJS community. As such a project requires, they are brilliant people with a high motivation. I’m playing with nodeJS for a while and I really like the idea of using Javascript for server side development. However, there are a couple of issues that are open to be solved or improved.

First of all, exception handling may easily become a problem. Since it’s in the very nature of Javascript development that you design your program in asynchronous blocks of code, in the deep levels of the code if an exception is thrown you may not catch it.

try {
// Any code inside this try-catch
// that makes an asynchronous call
// will be out of this scope.
} catch (e) {
...
}

This entry may help to understand the problem in more depth.

Actually, there is “uncaughtException” event thrown by process global object in such cases. This can be used as a last resort to prevent the server to go down at least. However, it does not help to recover from the exceptions in a healthy way. For instance, you won’t know which client request caused the exception which will cause the client response to be never ended. You may be while developing your code, however, this may not help when using 3rd party libraries.

Second problem of nodejs is about development habits. In nodejs, when you want to see the effects of your changes you should restart your server. At first sight, this does not seem to be a big problem. However, after a while, it becomes a very annoying problem. Because of that, my first toy project was to implement a dynamic module system to re-load a module when the file changes. However, this does not work in a smooth way and probably won’t work as expected under complex module dependency relations. (You may try yourself with process.watchFile and clearing the module cache which can be find in the source codes)

At the end, nodeJS wins in terms of being a cool project. For instance, I like Erlang, both the platform and language, however, the ability to use Javascript on server side is really exciting. People who had used Flash Media Server before should remember the joy of using JavaScript to develop applications.

Posted in nodejs | Leave a comment

First impressions about iPad…

My friend has bought an iPad for his sister and we had a chance to play with this new toy: a bright and clear screen with a smooth touch interface, fast and responsive applications and a very long-lasting battery in a thin and light tablet. I liked it.

There are many things to say about iPad but what I’ve found very important is that its screen size and keyboard is enough not only for browsing or reading but also for writing emails, documents, preparing simple presentations, that is, for producing content. In that respect, it can replace a notebook or netbook for simple daily tasks.

Second, there are many educational applications in the AppStore and there are many books for children. I think it’s not accidental that the iBooks application comes with a “Winnie the Pooh” story book. That is, iPad will be a good device for children to learn and enjoy. We can expect that the next generation will grow with such devices. At least the ones whose parents can afford an iPad.

Posted in sips | Tagged , | 1 Comment

Inside Steve’s Brain, who is Steve?

I’ve finished the book for a long time ago but I’ve forgotten it in the shelves till the launch of iPad. I’ll share my thoughts about the book and the main character of the book and then I’ll probably forget it again.

I think that the main character is not Steve Jobs but the CEO of the Apple who named Steve Jobs. The book is all about a man who made a successful business career in his life and who, for some, has changed the world. Of course, such a book is more about business for sure, but the final impression shouldn’t be that Steve Jobs is a entrepreneur and that is it. The Triumph of the Nerds was better in that respect that it portrays a “man” who does interesting thing in business.

Anyway, the book is divided in chapters about the different attributions of Steve Jobs, actually Apple. Focus, Despotism, Perfectionism and Elitism are some of them. Although some/most of these topics have a negative meaning, the author tries to validate them by the success of Apple. However, I’m not sure if cause-effect relation really holds here because I’m actually not sure if Steve Jobs or Apple really has these features in their strong versions. The company cannot have them in the strong sense because for instance the book also talks about team play and communication which cannot exists in a despotic environment.

Of course, it’s hard to believe that the author really thinks of an ideal place but at the end the whole book is written in such a tone. I don’t like this tone, hence I didn’t like the book that much.

However, to render unto Caesar that which is Caesar’s, there are two things I’ve been reminded by the book:

  1. It’s not correct that you should always listen to your customers because sometimes even customers themselves do not know what they want.
  2. It’s correct to follow your passions because you won’t have a second life or chance.
Posted in sips | Tagged , , | Leave a comment