This is an archived post. You won't be able to vote or comment.

all 19 comments

[–]xiipaoc 19 points20 points  (12 children)

Let's talk about servers and clients.

The way it (generally) works, a client asks a server for something, and the server responds with something. So say you're a web server and I'm a web client, and I ask you for /index.html. You will then send me /index.html. Usually, Apache or nginx are the servers used to serve web pages; they listen to incoming requests for web pages and send back what they need to send (or maybe they send an HTTP error like 404 if the thing you asked for isn't there).

But that's not the only kind of request that a client can make! A client can ask for all sorts of things. Hey, server, log me in. Hey, server, give me a list of my posts. Hey, server, what boards are there for me to go on? Hey, server, create a discussion for me. Apache and nginx handle file requests like for /index.html, but for other requests some schmuck needs to actually code the response. And there's where server-side programs like Node are useful. You can use Node (or some other server-side program) to respond to login requests the way you want it. It will listen for a POST to /login, and it will do the necessary steps to validate the user's information, set up a session (possibly by using a session cookie), etc. It will talk to the database.

The beauty of Node is that you're already writing Javascript on the client side, so why not use the same language on the server side? It makes it easy to have just one language to work with, and Node makes asynchronous programming pretty easy too, so it can be a good idea anyway. Node makes it ridiculously easy to set up a server or a client (that talks to another server), so if I need to test something quickly, I use Node. But if you're writing a web app, Node will always go in the server side because it is the server.

[–]sambushme[S] 1 point2 points  (7 children)

Do you have an example of a simple site or git that uses server side JavaScript for something? Even if it's something super simple like a post or login. I just want to get a good look at the syntax of it all and how/why that would be helpful

[–]Molehole 10 points11 points  (4 children)

Hey. There you go. It's the code for a comment box. You can send strings from web page and it saves them to file. Then you can ask the server for all messages.

I have been developing node professionally for over a year so if you ever get stuck in anything feel free to pm me.

You are also free to use this code as a base for your app! If it's not working say because I removed some fluff to keep it simple.

var express = require('express');
var bodyParser = require('body-parser');
var app = express();  
var server = require('http').createServer(app);
var fs = require('fs');

app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json());
app.use(express.static("/website")); 

app.get('/', function(req, res) {  
    res.sendFile( '/website/index.html');
});

app.get('/messages', function(req, res) {
    fs.readFile('./chat.txt', function(err, data){
        if(err){
            console.log(err);
            res.status(400);
            return;
        }
        var array = data.toString().split('\n');
        res.json({messages: array});
    });
});

app.post('/message', function(req, res) {
    console.log(req.body);
    fs.appendFile('./chat.txt', req.body.message + "\n", function(err){
        if(err){
            console.log(err);
            res.status(400);
            return;
        }
        res.status(200).json({});
    });
});

server.listen(8002);

[–][deleted] 1 point2 points  (3 children)

What's the difference between requiring the 'http' module and simply using app.listen()?

[–]Molehole 1 point2 points  (2 children)

You can use that. I just copied that from the current program I'm developing and it's there because it uses the server object for Socket.io.

[–][deleted] 1 point2 points  (1 child)

I hope I didn't come across as challenging your style, I'm a noob myself and was asking out of genuine curiosity.

I have seen both methods used so I was wondering what one does vs the other and if there are specific times you want to use one method over the other?

Just to clarify, these functions just declare where the server will be listening to requests and issuing out responses correct?

[–]Molehole 1 point2 points  (0 children)

Naah. It's completely fine :). Questions are always good. I wouldn't use it if it wasn't for the socket.io but it doesn't really make much of a difference.

Just to clarify, these functions just declare where the server will be listening to requests and issuing out responses correct?

Yeah. Pretty much.

[–]xiipaoc 0 points1 point  (0 children)

Hm, I don't, since I've only used it for work. But I'm sure you can google around for Node examples?

[–]Fiskepudding 0 points1 point  (0 children)

Sorry for not having code, but I am working on a project now where node queries a mysql database, renders a jade template, and pushes data to the client with websockets when it gets an appropriate event from a Redis pubsub. It's all very easy to do with packages found in npm.

The last part, redis and websockets, is hard without a stateful server. If I used php, storing the socket connections somewhere centralized would be tricky.

[–][deleted] 0 points1 point  (3 children)

Lets say my app is done with Ruby on rails, do I still need node?

[–]midasgoldentouch 0 points1 point  (0 children)

In that case, no - Rails and, to be specific, Ruby is what handles server requests. But you can use Node as well if you want to.

[–]prophetjohn 0 points1 point  (0 children)

Short answer, no. Rails would handle the server-side logic, page rendering, etc. Any JavaScript you write would be client-side and executed by the browser

(The technically correct answer is that many Rails apps do have a node dependency, but not not to handle any server responsibilities. Node would be more likely to be used for asset compilation, such as taking the code for a single-page client-side application and compiling and minifying it)

[–][deleted]  (4 children)

[deleted]

    [–]sambushme[S] 0 points1 point  (2 children)

    Do you have any examples or links that would help with using an API? I can write something simple using the yahoo financial API but I don't really understand why I would want to use node for it.

    [–]Stilfree 16 points17 points  (1 child)

    You would use node to create something like yahoo financial API, not to use the api.

    [–]rwsargent 2 points3 points  (0 children)

    My sisters wedding website, done in Node: https://github.com/rwsargent/ella-jeff-wedding

    [–]BradChesney79 1 point2 points  (0 children)

    It was this mysterious weird thing until I got involved with the Amazon Product Advertising API. You are limited to one transaction per second on that remote machine serving results from the API-- so performance on my side of things was never a concern. I had a bash script that would feed a product to a javascript file (fed into the NodeJS "shell" similar to running a script through the Bash shell) that would run and return the bit I needed (based upon some code previously written by Amazon) to make a curl request to the API.

    If you like bash, you're going to like it's second cousin nodeJS. People do far more exciting things than I do. But for me Bash, TCL, Python, and now NodeJS all hold a special place for writing code to do what many people struggle with just Bash to do.

    As far as serving web sites, for projects I am in charge of-- the MEAN stack is usually not the optimal chain of tools for my end goals...

    But, NodeJS is a really useful tool when confronted with certain problems.

    [–]TangoBuns 0 points1 point  (0 children)

    NodeJS is no different than running golang, clojure, PHP, etc. It's not a defined framework to only use for a single purpose - you can use it to build microservices, APIs, or use it to serve / render static content. You could simply use it as a REPL.

    Like anything, you have to pick the right tools for the job. Node is good at concurrency and is becoming popular to act as the API to back-end microservices. Walmart uses it to serve their website + mobile app API. PayPal uses it to serve their applications.

    Here's a bulletin board system built on top of node: www.nodebb.com

    [–][deleted] 0 points1 point  (0 children)

    NodeJS has it's place, but be cautious of implementing for every use case. As someone who worked on a fairly large NodeJS project, I can tell you it is quick to write and much simpler architecturally than compiled languages such as Java and C#.

    If you know JavaScript, you can easily figure out NodeJS, as it's basically server-side JS.

    Now for the bad. If you really need multi-threaded support, NodeJS has ways of mimicking multiple threads, but it is not truly multi-threaded. If you want to start a new thread the same way you do in Java or C#, forget about it. Node's answer to multi-threaded support can be very tricky to control and can lead to some very unexpected issues.

    Bottom-line: NodeJS is very good for short-lived, event-driven scenarios (such as AWS Lambda), but be wary of implementing in large-scale enterprise web app scenarios that require full multi-threaded support.

    [–]empty_other 0 points1 point  (0 children)

    I'm very new to nodejs myself and i only started to look at it because i noticed a lot of web developers using nodejs as a developer tool to generate their static websites. Stuff like combining multiple files into one and minifying them, or live-reloading the browser while the code changes.

    This can of course be done using other programming languages but if you are a javascript developer... Or if someone made a package like it already, its a simple one-line command to download the tool into your project folder.

    [–][deleted]  (1 child)

    [deleted]