How would MVC-like code work in Node.js? - javascript

I'm starting to get my head around node.js, and I'm trying to figure out how I would do normal MVC stuff. For example, here's a Django view that pulls two sets of records from the database, and sends them to be rendered in a template.
def view(request):
things1 = ThingsOne.objects.all()
things2 = ThingsTwo.objects.all()
render_to_response('template.html, {'things1': things1, 'things2': things2})
What might a similar node.js function look like?

http://boldr.net/mvc-stack-node-js-ejsgi-scylla-mustache is a great little article with a full github example of a MVC pattern using dirfferent Node modules. It also lists alternate modules currently available. It answered this question for me better than http://howtonode.org/ which has some good tuts but I couldn't find anything on MVC there.

The easiest way to do this is with expressjs, which is an MVC framework for Node. Node is just what it says, evented I/O for the web.
The example on the http://expressjs.com should help with the basics but to answer your question directly.
var express = require('express');
var app = express.createServer();
app.get('/whatever', function(req, res) {
Things1.objects.getAll(function(things1) {
Things2.objects.getAll(function(things2) {
var options = { locals: { things1: things1, things2: things2 }};
res.render('thingstemplate.ejs', options); // or thingstemplate.jade or whatever
});
});
});
app.listen('80', ''); // port and optional hostname to bind

TowerJS is a popular MVC framework based on
MongoDB (database)
Redis (background jobs)
CoffeeScript
Stylus
Jasmine (tests)
jQuery
Site http://towerjs.org/
Source https://github.com/viatropos/tower

RailwayJS is a MVC framework, written in JavaScript based on ExpressJS and runs over nodeJS platform. It is inspired by Ruby on Rails framework. You can read about MVC architecture of RailwayJS here: http://jsmantras.com/blog/RailwayJS-Routing

Related

where and how to use nodejs with angularjs

I am new to UI framework development. Currently my requirement is to work with anuglarjs and nodejs. I know there are few more like me who want to know the exact use..
I am confused as where i need to use nodejs in my application. I tried to find a simple live demo example(plunker/jsfiddle) which used angularjs and nodejs but i couldn't find one.
Currently i have written a small module using angularjs, which hits the java controller class and saves/get the data and display the data on the webpage. Here i'm no where using nodejs. I tried to search in web to understand the use of nodejs with angularjs.
Any input's would be very helpful.
Below is the sample javascript code i implemented using angularjs.
myDataCOntroller.js
//some code here
$scope.submitFormData = function(myForm){
if(myForm.$valid)
{
MyDataService.saveOrGetData($scope.myReport).then(
function(response) {
$scope.myReport = response;
},
function(errResponse){
console.error('Errorr');
});
}else{
console.log("invalid form data!!");
}
}
myDataService.js
app.factory('myService',function($http,$q,$location){
var MY_SERVICE_URI = $location.protocol()+'://'+$location.host()+':'+$location.port();
var _repServiceFactory={};
_repServiceFactory.saveOrGetData = function(myData){
var deferred = $q.defer();
var url = appURL+'/saveOrGetData.form';
$http.post(url,JSON.stringify(myData))
.then(
function (response) {
deferred.resolve(response.data);
},
function(errResponse){
console.error('Error while fetching data');
deferred.reject(errResponse);
}
);
return deferred.promise;
}
PS: I know that Angularjs is client side, Nodejs is server side, both are using Javascript programming language.
What i want to know is, what is the use of nodejs and where is it used in real time??
If you are writing an AngularJS front end web application, you may never have to use NodeJS.
If you need tooling (build scripts to compile Sass, linters, etc) in your development or deployment process you can use NodeJS task runners like Gulp, Grunt or Webpack.
If you need to build a back end API, that stores and retrieves information, you can use Express or the whole MEAN stack.
* * * Also worth noting-- you mention hitting a Java class. If you are already using Java for the backend, then you probably won't be using any NodeJS for that purpose. If you were just shortening JavaScript to "Java", please note they are separate and distinct languages. * * *
Web dev has 4 primary parts:
Back-End: Node.Js (which will replace or work with your Java server)
Front-End: Angular.js (or React/Polymer/Vue/etc.)
Database: MongoDB (noSQL), mySql/Postgres (sql)
Routing/Server/Middleware: Express.js
For you to create an app that is realtime, you can use websockets, especially Socket.io (which works really well with and is built for Node.js)
WebSockets are essentially bi-directional (low latency) event-based tunnels where data can be passed from client-to-server, and server-to-client without the need to make an AJAX (tcp) request per message.
This paired with a strong data-binding architecture (API -> Angular Binding) allows for customizable single page views, where the same data can be used to create a view, and update the back-end modal when the data gets updated.

Is it possible to use client side version of expressjs roure?

I need to use expressjs like routes on client side to be possible invoke callback function upon specific route like the following:
app.get('/dogs', function(req, res, next) {
// do stuff
});
Is there something like for client side?
I was looking for the same thing the other day, and I stumbled upon Page.js.
As the author describes it, it's a
Micro client-side router inspired by the Express router (~1200 bytes)
Plus, the original author is TJ Holowaychuk, the guy behind Express. So I guess Page.js and Express.js should have a few similarities :)
However, TJ posted on his blog about his departure from the Node.js world, so I don't know if he intends to maintain it.
Hope this helps.
Have you tried clint-side MVC frameworks like Ember, Angular, Bankbone(http://backbonejs.org/) etc?

REST API Node.js, organization

I m actually developping a REST API using Node.js and Express 4.0 and I wanted to clarify something.
The service is actually working, but in a single javascript file, and I m looking for a good way to cut it into multiples parts.
I was thinking about MVC, but with the actual route system, what is the controller ? Is it the declaration function of the route ?
How can I separate the different route into multiple files ? (like user_routes, billing_routes) etc... I know how to export module etc... but having app = express() in multiple file seems to not work (different instanciation)
And where to start to the listen the part ?
These are beginner questions, but please, but explicit :-)
Thanks for advance
You can check out some these examples:
mvc: https://github.com/visionmedia/express/tree/master/examples/mvc and
route-separation: https://github.com/visionmedia/express/tree/master/examples/route-separation
Also here there are 2 good posts on SO about the subject:
https://stackoverflow.com/a/13611448/2846161
ExpressJS How to structure an application?

Advice on creating a micro-framework in JavaScript

I'd like to know what are the steps required to create a framework on top of node.js.
I believe this can be a good way to learn, that's why I'm doing this!
I've been checking other micro-frameworks and bigger frameworks but I'm not being able to understand where to start. I'd like your advice on this.
Edit: MVC Framework like Sinatra, Merb, Rails.
For an MVC framework, the basic concepts go something like this (forgive the simplicity):
var view = 'I say, "{{first}} {{second}}".';
var model = {
first: 'hello',
second: function(){
return 'world';
}
};
for(item in model){
var regex = new RegExp('{{' + item + '}}', 'gi');
if(typeof(item) == 'function')
view = view.replace(regex, model[item]());
else
view = view.replace(regex, model[item]);
}
console.log(view);
Start as simple as possible and add small enhancements:
Store views/templates as files. This gives you a chance to play with node.js's async file I/O.
Add support for more complex models - repeating items/arrays, objects containing objects
Add support for templates inside templates
Fetch your models from an external datasource. CouchDB might be fun.
Add proper controllers - these objects should know which models go with which views and how to stitch them together
Map your Http request urls to controllers and actions - /person/55 might fetch a person with id 55 from your data repository, /person/add might bring up a UI to add a person - both use a person controller with views displayed for the appropriate action.
Take a look at mustache.js for a small template engine. Note their terminology differs from mine in examples and code. What I call a view, they call a template and what I call a model, they call a view. It's a small thing but potentially confusing.
Additional resources:
A giant list of node modules. Includes templates, database, routing, and full frameworks.
MVC with Node.js - Which modules?
Root.js : A Skeletal MVC Framework for Node.js

How to design a Library?

We have just started our new assignment - web-based project. Before I get directly on to the question it would be necessary to explain about the project.
We are actually moving a product from desktop to web. This is it. All backend services are web services. Our choice of server technology will be .NET. As we are good with it and also client are equipped with it too. So, we will be doing all the server work in ASP.NET AJAX. PageMethod will be preferred choice to communicate with server (C# 3.0) and client (JavaScipt). There will be a real need of jQuery for parsing DOM and XML parsing. We do not to put effort to reinvent the wheel.
Now, there are things what we have to do and mostly it will be in JavaScript. We would like to package it in one.
E. John did a very useful session on 'Building a JavaScript Library' which is very useful. It surely keep in this way.
A fairly good amount of JavaScript engineers are here. And I would like to have their recommendations and suggestions before we start over.
Do you know some good references on JavaScript Library design? If you every made your own JS Library what you learned from it? Have you look into gmail/googledocs/facebook JavaScript? What have you learned from it?
Thanks.
Start off with something like this:
var yourNamespace = yourNamespace || (function () {
"use strict";
// private variables here
return {{whatever you want yourNamespace to be here}};
}());
To design a javascript library -
Identify what functions you write often.
Save them in a seperate .js file.
Keep a log or comment block on top
of the development version and
update to reflect the contents of
the file.
Done.
Use a webservice for connect to db and exec the queries..
Create SERVICE.JS, in this file call web service with jquery.ajax method
Create a DESIGN.JS, in this file do everythig about user ınterface (onclick, initialize,fill grids,combos etc)
Create a GLOBAL.JS, in this file create global variables for use everywhere(for example: UserId)
Create a HELPER.JS, in this file create useful functions for use anywhere(for example: function DATE_TO_STRING(_date) )
On this all .JS files use namespaces example for GLOBAL.JS:
(function () {
var GLOBAL = {
CurrentUserId:-1
}
if (!window.GLOBAL) { window.GLOBAL = GLOBAL; }
})();
Dont use ASP.NET components. Use html inputs,textarea etc

Categories