Welcome!

Join our community of MMO enthusiasts and game developers! By registering, you'll gain access to discussions on the latest developments in MMO server files and collaborate with like-minded individuals. Join us today and unlock the potential of MMO server development!

Join Today!

Useful Node.JS tutorials/starter kits

Joined
Jun 8, 2007
Messages
1,985
Reaction score
490
Hi all, this thread is reserved for those who know of or want to know of excellent resources for learning and performing with Node.JS. All things Socket.IO, Express.JS, MongoDB, and Node.JS are welcome! Let's try to keep things like spidermonkey out because, seriously, Node.JS is clutterred enough, let's work on getting some utilities and coding guidelines together so that more people can start using Node.JS today!

Make sure everyone gets a copy of Node.JS, and NPM (node package manager) so that it's trivial to install packages such as express, socket.io, mongodb, and more!

I'm making some pretty cool stuff with node.js, and I'll be sure to post some code examples/tutorial later on.

I'm hoping the community here at RZ may help me to gather up a good bundle of information for Node.JS.


Okay. Anyone who's gone so far as to download Node.JS has probably tried this famous HTTP server example from nodejs.org:
PHP:
var http = require('http');
http.createServer(function (req, res) {
  res.writeHead(200, {'Content-Type': 'text/plain'});
  res.end('Hello World\n');
}).listen(1337, '127.0.0.1');
console.log('Server running at http://127.0.0.1:1337/');
If you're going to make a web app to print some text to a browser on every request, then this example is for you. Okay let's get back to real life now. The above example compares wonderfully to other hello world servers, but I can't think of any production-level server where the goal is that simple. The truth is, once you try to get a little deeper into Node.JS following the above semantics, you run into spaghetti code very fast. The reason for that is "Callback Madness."

Okay, so let's do a similar thing with express:
PHP:
var express = require('express');
var app = express();
app.get('/', function (req, res) {
    res.send('Hello, World!');
});
app.listen(8000);
console.log("Server is listening on port 8000.");
The above code will not respond 'hello world' on every request, I only told express to respond that for '/'. Nothing else is defined. So if you visit you will see 'Hello, World!'. But if you visit you will see something like 'Cannot GET /foo' because express fails a little safer than and is a little more helpful for HTTP than the built-in HTTP module is.

If you don't have express installed, but you do have npm, you can (in your command prompt/terminal) type: "npm install express" to install express.js!

So, there's no immediate proof that express solves the callback problem, so let's dig a little deeper. At the moment you may be thinking: What exactly does S-p-n mean by "Callback Madness"? That node.JS example looks easy- perhaps just as simple as express.

So let's try to make the Node.JS HTTP module example server listen on '/'- just like express module is doing.
PHP:
var http = require('http');
http.createServer(function (req, res) {
    res.writeHead(200, {'Content-Type': 'text/plain'});
    switch (req.url) {
        case '/':
            res.end('Hello World\n');
        default:
            res.writeHead(404);
            res.end('Could not GET ' + req.url);
    }
}).listen(8000);
console.log('Server running at http://localhost:8000/');

Okay, not so bad, but there's already a noticeable complexity problem arising under our nose. What happens if we want to add more requests? What happens if we want to host a file server like many other HTTP servers do? Well, there's modules to help us with that, but there's even better modules that do most of the heavy lifting for us.

Don't get me wrong, I tried to make a sustainable Node.JS file system module, and a sustainable Socket.IO module already- I don't give up that easily. And it's really not that I gave up, it's that there are people spending just as much time on express as I am on my custom stuff (well, probably more). Using the HTTP library you would need to include the 'fs' library or similar, and you'll have to do some crazy heavy-lifting like I did to make a good file-server with gZip compression and so on. Actually, it's probably a good 50 lines of JavaScript- possibly more if you want to add any cool dynamic magic to the mix. That's not too bad, so it's possible to scale Node.JS into a maintainable production-level server. But there's already an easier way.

Here's how to host a file-system in express:
PHP:
var express = require('express');
var app = express();
app.get('/', function (req, res) {
    res.send('Hello, World!');
});
app.get('/:file', function (req, res) {
    res.sendfile(req.params.file);
});
app.listen(8000);
console.log("Server is listening on port 8000.");

Notice there's no callback madness- the deepest level is still 1 tab

So now it's possible to load the server file, I named mine 'test.js' so when I visit I get the code above. Now, you're probably thinking all sorts of red security flags right now. Well, you have good reason. Not many people want to push their server-side code to the browser. But it gets worse- well, it would get worse, but express protects us from even more evil scenarios such as this command:
Code:
curl http://localhost:8000/../passwd.txt
When you build your own file server, you need to worry about all of these security concerns. When you're using express, you need to think about these concerns, but with a little less uncertainty.

We are certain our server-side code is available, and we can make just as certain the files are safe by placing the file-system we want to serve in a public directory. It's no surprise files from ./public are going to be public, so it's a little easier for web developers to think about security. If you don't put spooky files in ./public, then you don't need to worry about spooky things. Simple. So let's partition a public directory using app.use.
PHP:
var express = require('express');
var app = express();
app.use(express.static(__dirname + '/public'));
app.get('/', function (req, res) {
    res.send('Hello, World!');
});
app.listen(8000);
console.log("Server is listening on port 8000.");

On line 3 I added a line that will serve a static file-system. That's one of express' built-in helpers. So now all you have to do is create a folder named "public" in the same directory as the server, and you can use this in production for static web-sites. But that's very boring. I realized that, rather than concerning about POST, PUT, DELETE, and anything except GET is frivolous anymore. Instead, I use Socket.IO for IO (instead of AJAX/GET/POST/PUT/DELETE and hundreds of files- I just think about x number of channels, each with incoming/outgoing emits and outgoing broadcasts), and GET for the initial page. I, personally, prefer to develop for HTML5/CSS3/ES5 than I care to worry about older or partially supporting browsers. You never need to send attachments anymore, as you can just send the file through a web socket, and use the local filesystem API to allow users to download files on the fly. That's only one of hundreds of use-cases for HTTP that can be done with less effort using web sockets.

Well, at the moment web socket support is beginning to become consistent, but for a while there every version of Chrome I installed broke my web socket application. I decided web sockets weren't for me, but then I rediscovered Socket.IO. Socket.IO will stubbornly try to make your sockets work in situations as ugly as IE5.5. Why, I don't know.. But if you're trying to target the most up-to-date browsers, socket.IO is nothing of a downfall- it certainly tries to use the best possible case for your browser. Whether it will or not, I don't know and don't care- but I do know that even browsers that support web sockets, the protocol was very hard to match across browser a year back. So for a full year, I haven't tried implementing my own sockets- Socket.IO is the cream of the crop for me, but you can do whatever you like.

Well, I made a little utility for Node.JS which uses Socket.IO and express, and I'm thinking of improving the DB with Mongodb, but many developers are using MySQL, MSSQL, basic JSON and various other things instead of Mongodb. There are lots of people trying MongoDB, and I encourage the use of that over the alternatives. I think Node.JS technologies are beginning to pass the test of web-time.

Okay I uploaded a repo to github with a maintainable example server using a file system of web apps, socket.IO, and mongoDB all on top of express.


(Information moved to github)

To be continued...
 
Last edited:
Banned
Banned
Joined
Feb 14, 2007
Messages
1,405
Reaction score
220
That's so nice but i think I'm going to start with HTML Then CSS Then PHP
 
Joined
Jun 8, 2007
Messages
1,985
Reaction score
490
i quoted the word php, so

PHP: faster, but failing.
PHP: the biggest mistake u can do.
my funny conclusion: rather learn node.js. xD

ive no idea whats the problem ... -.-
I agree with your conclusion, but the sad truth is that PHP has a very large set of built-in functions and pre-loaded extensions, rendering it quite slow to interpret for humans and computers. JavaScript is a very tiny programming language, and the work the guys put in over there at V8 puts JavaScript against languages closer to machine code ~~~ so you would rather compare JavaScript to C than PHP.

I don't know what you meant by "faster" but in any case I can think of, JavaScript is the winner of that, too. The biggest advantage to PHP over Node.JS is for Apache2 developers, people who like huge tool-kits to work with, and people who like the most popular dynamic server-side configuration. I'm not going to call PHP an advantage to people who already use PHP professionally, because I feel those people -most people- are stuck with their configurations, making PHP a disadvantage overall- much like the way .NET is a disadvantage for windows developers expanding to other platforms such as Android or IOS. Don't get me wrong, .NET and PHP are very large tool-kits and are very popular- so weighing the advantages with the disadvantages, they are both very powerful.

I think of Node.JS as freedom- but like early pioneers, we as developers have to pave many roads in this new land. Developers coming from Apache2 and PHP or .NET will be smacked with reality when they look for a toolkit and the only answer they get is "there isn't a toolkit for that yet, but you can make one." As far as development speed goes, it really depends on the competence of the developer and largely what they are developing whether PHP or Node.JS is the right choice. There is also a little room for PHP to work along-side or under Node.JS, but I have yet to see a fully-functional PHP module for Node.JS. I did get a test case of PHP kind-of working under Node.JS with CGI, but somebody is going to have to spend much more time than I have to spend on that. I had (input) GET/POST working had COOKIES/SESSIONS almost working, and somebody else in the world (separate project) got PHP working with output. Given our different implementations (he used FastCGI and I just used an unstandard CGI hack). So there's hope that PHP developers who aren't strictly tied to Apache2 may switch to Node.JS and keep their PHP.
 
Last edited:
• ♠️​ ♦️ ♣️ ​♥️ •
Joined
Mar 25, 2012
Messages
909
Reaction score
464
I agree with your conclusion, but the sad truth is that PHP has a very large set of built-in functions and pre-loaded extensions, rendering it quite slow to interpret for humans and computers. JavaScript is a very tiny programming language, and the work the guys put in over there at V8 puts JavaScript against languages closer to machine code ~~~ so you would rather compare JavaScript to C than PHP.
the large set of build-in functions of php were created to provide a programming language that is easy to handle and code. in fact, in the beginning php was not meant to be a programming language at all. im not familiar to node.JS to be honnest, so i cant say how big the pre loaded stuff of node.js is.

I don't know what you meant by "faster" but in any case I can think of, JavaScript is the winner of that, too. The biggest advantage to PHP over Node.JS is for Apache2 developers, people who like huge tool-kits to work with, and people who like the most popular dynamic server-side configuration. I'm not going to call PHP an advantage to people who already use PHP professionally, because I feel those people -most people- are stuck with their configurations, making PHP a disadvantage overall- much like the way .NET is a disadvantage for windows developers expanding to other platforms such as Android or IOS. Don't get me wrong, .NET and PHP are very large tool-kits and are very popular- so weighing the advantages with the disadvantages, they are both very powerful.
with "faster" i meant the programming speed for the developer. im sry i didnt clear that out good. you are right, javascript is the winner for sure, cuz php becomes slow on execution due all the pre loading stuff that provides to code on an easier way that is absolutly ridiculous. in any case i would suggest ppl to learn ANY other language before learning php, javascript is actually a good language that provides a stricter syntax/type/operator handling.
but lets get a true point, scripting is not the solution on real server-sided projects. both are script languages, but php at least provides a good understanding OO model. javascript provides a prototype OO model, but its just a bunch of sh*t. at the end i wouldnt suggest anything of that as programming language for a service at all. server sided u need a high language for the best results. client sided u can use your javascript for simple realtime interactions with your website, nothing more (... JavaScript), nothing left (our case of 99% of webusers who got javascript enabled).

on the .NET part u got a point, but there are still libraries who allow to convert those things, i mean look at mono for android. sadly its more or less faked since it converts your .NET code to java.
btw, there are many proffesional php coders for sure, but u should ask them how much of their time they spend on checking types of variables and converting stuff around or trying to find any disbehaviours without any clue ...

I think of Node.JS as freedom- but like early pioneers, we as developers have to pave many roads in this new land. Developers coming from Apache2 and PHP or .NET will be smacked with reality when they look for a toolkit and the only answer they get is "there isn't a toolkit for that yet, but you can make one." As far as development speed goes, it really depends on the competence of the developer and largely what they are developing whether PHP or Node.JS is the right choice. There is also a little room for PHP to work along-side or under Node.JS, but I have yet to see a fully-functional PHP module for Node.JS. I did get a test case of PHP kind-of working under Node.JS with CGI, but somebody is going to have to spend much more time than I have to spend on that. I had (input) GET/POST working had COOKIES/SESSIONS almost working, and somebody else in the world (separate project) got PHP working with output. Given our different implementations (he used FastCGI and I just used an unstandard CGI hack). So there's hope that PHP developers who aren't strictly tied to Apache2 may switch to Node.JS and keep their PHP.
i think node.js is still very interesting, dont get me wrong above, i dont say u shouldnt go that way, i just say i wouldnt go that way. xD
its still better than php for my part, cuz it doesnt throw u in the cold water of hidden exceptions i hope so. its interesting u got the ideas to build a toolkit + framework for such this, but your ideas go in the wrong way in my eyes. for what u want to combine node.js with php? if they want to stay php, they shouldnt use node.js, otherwise u increase the loadtimes by huge and provide a language with a bad OO model and another language with tons of exceptions that arent shown. to let it work with CGI on the position of PHP is might better, PHP developers introduced all the bad stuff by failing in their perl code, its not the fault of perl at all.
so, using CGI to build a node.js + php framework combine toolkit system sounds ridiculous in my ears.

if u want to provide a revolution for javascript, develope a lib that gives possibilities for classical OOP in javascript or just in node.js.
mein Senf dazu, or how u english ppl say: my two cents
 
Joined
Jun 8, 2007
Messages
1,985
Reaction score
490
@VibeTribe,

JavaScript doesn't support Object Oriented Programming. PHP Doesn't support prototypical inheritance. Who's to say which style is better/worse? Twilight-Zone taught me something- and I quote: "beauty is in the eye of the beholder." I don't like to compare things like this, it's like comparing the benefits of night vs day.

One thing I know for sure, it would be very bad if a language tried to support both styles- which is a direction PHP is currently heading.

The direction I'm heading currently is a framework written in JavaScript to enhance web development as a whole. The framework runs in Node.JS and in the web browser. Extensions are also written in JavaScript, but can be implemented in any language- notably C++ Node modules- but also in languages such as PHP or Python via the asynchronous command execution module, "exec."

Node.JS modules are not loaded until you load them using require(). PHP just does it differently by loading all of the extensions up-front so the programmer doesn't have to. How nice of the PHP dev to do that for us... As we all should know, pre-mature optimization may just be the root of all evil. The way PHP loads extensions is genius in the sense programmers don't have to worry about which toolkit/module they are using. They don't have to research any of that half the time- the PHP developer simply goes to PHP.net and all of the built-in extensions are bundled together at the same place. If everything there is will surely by there, then there is no reason to think about packing your bags. PHP can very easily optimize simply by using an autoloader (lazy-loading) technique. Not bad.. Not bad at all. The downfall I explained above- heavy toolkits take longer to learn, and at this point PHP5.4's entire function reference is probably impossible for any one human to remember by heart. Who needs to, though- if the reference is surely going to be there, there is no reason to think about packing your bags.

*Less thinking = a good thing.


Back to my goals... I'm not trying to shim PHP inside Node.JS... I tried way-back-when, but that lasted like, 2-4 days of hacking, I got a little excited, showed some friends and moved onto something more important since then.

What I am trying to do:

Most people don't like coding asynchronous JavaScript sites/webapps, but lots and lots of people want to make asynchronous JavaScript sites/webapps. I'm putting my money on the idea the people who want AJAX-driven web-sites are going to know HTML. For that reason, my framework will concentrate more on developing in HTML5 and utilizing data-attributes to do wonderful intuitive things. As I've worked out many quirks since I made this thread, the current thing on github is not up-to-date. Since then I implemented more listeners, improved components and modular functionality, and have made HTML5 more like a web-development language from a word document markup language. Utilizing Socket.IO and data-attributes, the finished framework should theoretically work in legacy browsers better than AngularJS.

The difference between what I'm trying to do and what the AngularJS framework tries to do, is that my framework not only affects the way client-websites are developed, but it also enforces an extensions/plugins layout on the server. Plugins/extensions are preloaded when the server is started, and they are compiled and ready to be used by the time they are needed.

Much like Apple feels their devices should couple hardware with software, I feel my framework should couple the server with the client. A web-app is really only "one thing" in the end. Sure, it may work on umteen devices, and it may have different clients for each of those devices, or it may have just one client that works on a known set of devices. In the end, the web-app should do the same thing, and in order for the end-user to get the best experience, the web-app needs to be developed in such a way the server and clients live together with synergy. Apache2 is a catch-all server, and jQuery is a catch-all client framework. The framework I'm working on is a catch-all web development platform.

For best compliance with JavaScript, I'm using MongoJS module for the database. I find MongoJS module (ironically) follows MongoDB's database query syntax much better than the MongoDB module the DB engine suggested I use. So the end result? I can use the to quickly transfer my MySQL skills over to MongoDB.

The release date? Expected to be released for testing towards the beginning of next month (September).
 
Last edited:
• ♠️​ ♦️ ♣️ ​♥️ •
Joined
Mar 25, 2012
Messages
909
Reaction score
464
youre right, its wrong to compare php and node.js at all haha.

well i finally got your point and idea u are looking too. many ppl call the possible result as web v2, websites who interact more with javascript ajax calls than with simple http requests via site reload.
if i got u right, youre heading to something similar microsoft provides with asp.net. they provide many possibilities to combine client and server with many effective ways, such as many extensions.

but wait, did u say less thinking is better? might better for newbies, but i dont like shorted progresses for a better result that isnt stable at all. xP

youre project seems to be interesting, even if i wont use it im curious of the result.
once there is an alpha/beta, please show off the included possibilities in a presentation.

thank you.
 
Back
Top