William Jiang

JavaScript,PHP,Node,Perl,LAMP Web Developer – http://williamjxj.com; https://github.com/williamjxj?tab=repositories

Tag Archives: NodeJs & Express

NodeJS apps

NodeJS packages for quick retrieving

Here I list some Node.js packages for quick retrieving:

  • Twitter Bootstrap:
    Simple and flexible HTML, CSS, and JavaScript for popular user interface components and interactions.
  • Less CSS:
    The dynamic Stylesheet language. LESS extends CSS with dynamic behavior such as variables, mixins, operations and functions. LESS runs on both the client-side(Chrome, Safari, Firefox) and server-side, with Node.js and Rhino.
  • Everyauth:
    Authentication and authorization(password, facebook, twitter & more) for Node.js.
  • Mongooes-auth:
    User authentication plugin for mongoose Node.js ORM
  • Node-inspector:
    Node Inspector is a debugger interface for Node.js using the WebKit Web Inspector.
  • Jade:
    Jade is a high performance HTML template engine.
  • Backbone:
    Backbone.js gives structure to web applications
    by providing models with key-value binding and custom events, collections with a rich API of enumerable functions, views with declarative event handling, and connects it all to your
    existing API over a RESTful JSON interface.
  • MongoDB:
    MongoDB is a scalable, high-perfomance, open-source NoSQL Database.
  • Redis:
    Redis is an open source, advanced Key-value store. It is often referred to as a data structure server since Keys can contain strings, hashes, lists, sets and sorted sets.

These modules can be found in github which can use npm install or git clone directly; for others, use wget, or apt-get to install.

NodeJS: module.exports

JavaScript Classes, Prototypes, and Closures

Here is a helpful video regarding on NodeJS – how to write the JS codes:
http://nodetuts.com/tutorials/28-javascript-classes-prototypes-and-closures.html#video.
I collected the sample codes and list here for quick retrieving:

var Adder = function(a, b) {
	this.a = a;
	this.b = b;
};
Adder.prototype.add = function() {
	return this.a + this.b;
};
module.exports = Adder;
--> node
> Var Adder = require('./adder');
> Adder [Function]
> var adder = new Adder(1,2);
> adder {object}
> adder.__proto__ { add: [Function] }

---------- 2. Add default --------
var Adder = function(a, b) {
	this.a = a;
	this.b = b;
};
Adder.prototype.coalesce = function() {
	if(! this.a) { this.a = 0; }
	if(! this.b) { this.b = 0; }
};
Adder.prototype.add = funciton() {
	this.coalesce();
	return this.a + this.b;
}
module.exports = Adder;

--> node
> var Adder = require('./adder');
> var adder = new Adder(1);
> adder.add()
> adder.__proto__.coalesce = funciton() {}
> adder.add()
> adder.a
------ 3. Avoid expose: closure -----
var Adder = function(a, b) {
	function coalesce() {
		if(! a) { a = 0; }
		if(! b) { b = 0; }
	};
	this.add = function() {
		coalesce();
		return a + b;
	}
};
module.exports = Adder;
--> node
> var Adder= require('./adder');
> var adder = new Adder(1,2);
> adder
> adder.add();

----- 4. Remove new: return {} ------
var Adder = function(a, b) {
	function coalesce() {
		if(! a) { a = 0; }
		if(! b) { b = 0; }
	};
	function add() {
		coalesce();
		return a + b;
	}
	return {
		add: add
	};
};
module.exports = Adder;
--> node
> var Adder= require('./adder');
> var adder = Adder(1,2);
> adder.__proto__
> adder.add()

----- 5. working with Node's modules as an event emitter ------
var EventEmitter = require('events').EventEmitter;
var Adder = function(a, b) {
	var that;
	function coalesce() {
		if(! a) { a = 0; }
		if(! b) { b = 0; }
	};
	function add() {
		coalesce();
		that.emit('add', a, b);
		return a + b;
	}
	that {
		add: add
	};
	that.__proto__ = EventEmitter.prototype;
	return that;
};
-->node
> var Adder = require('./adder');
> var adder = Adder(1,2)
> adder.on('add', function(a,b) {
	console.log('ADDING', a, 'and', b);
});
> adder.add();

NodeJS & Express: upload image file and refresh ALL linked screen (4)

NodeJS & Express: upload image file and refresh ALL linked screen (2)

This is the client-side codes for auto refresh web-screens when uploading image.

<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Node Practical Test - William Jiang - upload Image from local machine</title>
<link rel="stylesheet" type="text/css" href="stylesheets/style.css" />
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
<script src="http://malsup.github.com/jquery.form.js"></script>
<script src="/nowjs/now.js"></script>
<script>
$(document).ready(function() {

status('Choose a image file to upload:)');
now.receiveMessage = function(message){
  $(message).addClass('img_space').appendTo('div.display');
}

$('#uploadForm').submit(function() {    
  $(this).ajaxSubmit({
    error: function(xhr) {
      status('Error: ' + xhr.status);
    },
    success: function(response) {
      if(response.error) {
        status('Opps, something bad happened');
        return;
      }
    var imageUrlOnServer = response.path;
    status('Success, file uploaded to:' + imageUrlOnServer);
    var img = '<img src="'+imageUrlOnServer+'" title="'+imageUrlOnServer.replace(/.*\//, '')+'" />';
    // fresh all online pages.
    now.distributeMessage(img);
  }
 });	
 // Have to stop the form from submitting and causing a page refresh - don't forget this
 return false;
});

function status(message) {
  $('#status').text(message);
}

$('#userPhotoInput').change(function(e) {
  e.preventDefault();
  $('#uploadForm').submit();
  return false;
});
});
</script>
</head>
<body>
<div class="box">
  <h2>Image Stream</h2>
  <hr />
  <p>In the field, input the full URL to your image. You can use the 'Post Image' button to upload it.</p>
  <div class="main">
    <form id="uploadForm"
          enctype="multipart/form-data"
          action="/api/photos"
          method="post">
      <input type="file" id="userPhotoInput" name="userPhoto" size="50" />
    </form>
    <div id="status" />
    <div class="display"></div>
  </div>
</div>
</body>
</html>

The codes include all basic features: placeholder, validation, mouse locator, sync auto refresh, google CDN, ‘onChange’ event to auto upload, dynamic warning/error display, etc.

Plus the Server-side app.js, and css file which is simple and not list here, the application looks very cool!

NodeJS & Express: upload image file and refresh ALL linked screen (3)

NodeJS & Express: upload image file and refresh ALL linked screen (1)

This is my an other application o NodeJS – Use NodeJS and Express web framework to implement a very cool effect:

  • in the webpage, there is a file upload form; user can upload image files from here.
  • when submit, the image is uploaded to server directory, and reflect to current webpage without page refresh.
  • meanwhile, all the web users could immediately see this uploaded image without refresh.
  • exact the same as Facebook’s ‘like’ feature.

It is different from previous example, which doesn’t use upload form, instead, it uses a simple form input field. The forms are different, so the implement are quite different also. The following is the core app.js:

var my_dir = __dirname+'/public/';
var express = require('express'),
    routes = require('./routes');
var app = module.exports = express.createServer();

app.configure(function(){
  app.set('views', __dirname + '/views');
  app.set('view engine', 'jade');
  app.use(express.bodyParser());
  app.use(express.methodOverride());
  app.use(app.router);
  app.use(express.static(__dirname + '/public'));
});

app.configure('development', function(){
  app.use(express.errorHandler({ dumpExceptions: true, showStack: true }));
});

app.configure('production', function(){
  app.use(express.errorHandler());
});

// Routes
app.get('/', function(req, res){
 //app.get('/', routes.index); first time load ~/public/index.html
 var html = require('fs').readFileSync(__dirname+'/public/index.html');
 res.end(html);
});

app.post('/api/photos', function(req, res) {
 console.log(JSON.stringify(req.files));	
 var serverPath = '/images/' + req.files.userPhoto.name;
	
require('fs').rename(
 req.files.userPhoto.path,
 my_dir + serverPath,
 function(error) {
  if(error) {
   res.send({
    error: 'Ah crap! Something bad happened'
   });
   return;
  }
  res.send({
   path: serverPath
  });
 });	
});

app.listen(3000, function(){
 console.log("Express server listening on port %d in %s mode", 
  app.address().port, app.settings.env);
});
var nowjs = require("now");
var everyone = nowjs.initialize(app);

everyone.now.distributeMessage = function(message){
 everyone.now.receiveMessage(message);
};

It is not perfect, but it works fine. The core part is the callback for app.post -> ‘/api/photos’.
In the following blog, I will list brief client-side code.

NodeJS & Express: get URL image and refresh ALL linked screen (2)

NodeJS & Express: get URL image and refresh ALL linked screen (2)

This is the client-side codes for auto refresh web-screens when uploading image.

<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Node Practical Test - William Jiang - upload Image from URL</title>
<link rel="stylesheet" type="text/css" href="stylesheets/style.css" />
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
<script src="http://malsup.github.com/jquery.form.js"></script>
<script src="/nowjs/now.js"></script>
<script>
$(document).ready(function() {
 now.receiveMessage = function(message){
  $(message).addClass('img_space').appendTo('div.display');
 }
 $('#uploadForm').submit(function() {
   var str = $('#userPhotoInput').val();
   if(str=='' || /^\s+$/.test(str)) {
    status('Error: please input full URL!');
    $('#userPhotoInput').focus();
    return false;
   }
   var expr1 = /(http|https|ftp):\/\/(\w+:{0,1}\w*@)?(\S+)
     (:[0-9]+)?(\/|\/([\w#!:.?+=&%@!\-\/]))?/gi;
   var re1 = new RegExp(expr1);
   if(! str.match(re1)) {
    status('Error: please input a correct URL');
    $('#userPhotoInput').select().focus();
    return false;
   }
   var expr2 = /\.(gif|jpg|jpeg|png|ico|bmp)$/gi;
   var re2 = new RegExp(expr2);
   if(! str.match(re2)) {
    status('Error: please input a correct image file.');
    $('#userPhotoInput').select().focus();
    return false;
   }
   $('#status').fadeOut(100);
    
   $(this).ajaxSubmit({
    error: function(xhr) {
    status('Error: ' + xhr.status);
   },     
   success: function(response) {
     if(response.error) {
      status(response.error);
      return;
     }
     var imageUrlOnServer = response.path;
     var img = '<img src="/images/'+imageUrlOnServer+'" 
        title="'+imageUrlOnServer+'" />';
     // fresh all online pages.
     now.distributeMessage(img);
   }
  });
  return false;
 });

 function status(message) {
  $('#status').addClass('warning').text(message).fadeIn(100);
 }	
});
</script>
</head>
<body>
<div class="box">
  <h2>Image Stream</h2>
  <hr />
  <p>In the field, input the full URL to your image. 
      Use the 'Submit Image' button to upload it.</p>
  <div class="main">
    <form action="/api/photos" method="post" id="uploadForm">
      <input type="text" name="userPhotoInput" 
       id="userPhotoInput" placeholder="specify image URL...." 
       data-prompt-position="topLeft" autocomplete="on" size="50" />
      <input type="submit" value="Submit Image" />
    </form>
    <div id="status"> </div>
    <div class="display"></div>
  </div>
</div>
</body>
</html>

The codes include all basic features: placeholder, validation, mouse locator, sync auto refresh, google CDN, ‘onChange’ event to auto upload, dynamic warning/error display, etc.

Plus the Server-side app.js, and css file which is simple and not list here, the application looks very cool!

NodeJS & Express: get URL image and refresh ALL linked screen (1)

NodeJS & Express: get URL image and refresh ALL linked screen

Use NodeJS and Express web framework to implement a very cool effect:

  • in the webpage, user inputs a URL to upload a image
  • when submit, the image is uploaded to server directory, and reflect to current webpage without page refresh.
  • meanwhile, all the web users could immediately see this uploaded image without refresh.
  • exact the same as Facebook’s ‘like’ feature.

Traditional technology such as PHP & DB do not have such features, only the server-side JavaScript NodeJS can do. I googled all around but can not find an effective and existed solution; so I have to do by myself.

After trying several ways, finally by using request module, I made it work. Here I list for sharing when some people want to do the same thing. The following is the core app.js:

var my_dir = __dirname+'/public/images/';
var express = require('express'), 
 routes = require('./routes'),
 request = require('request'),
 fs = require('fs');
var app = module.exports = express.createServer();
app.configure(function(){
  app.set('views', __dirname + '/views');
  app.set('view engine', 'jade');
  app.use(express.bodyParser());
  app.use(express.methodOverride());
  app.use(app.router);
  app.use(express.static(__dirname + '/public'));
});
app.configure('development', function(){
  app.use(express.errorHandler({ dumpExceptions: true, 
     showStack: true }));
});
app.configure('production', function(){
  app.use(express.errorHandler());
});

app.get('/', function(req, res){
 var html = fs.readFileSync(__dirname+'/public/index.html');
 res.end(html);
});

app.post('/api/photos', function(req, res) {
 console.log(JSON.stringify(req.body));
 var serverPath = req.body.userPhotoInput.replace(/.*\//, '');
 var path = my_dir + serverPath;
 console.log(path);
 console.log(serverPath);
	
 var ws = fs.createWriteStream(path);
 var r = request({url:req.body.userPhotoInput, res:res}, 
  function (error, response, body) {
  if (!error && response.statusCode == 200) {
   res.send({ path: serverPath	});
  }
  else {
   res.send({ error: 'No such image file!' });
  }
 }).pipe(ws);
});

app.listen(3001, function(){
 console.log("Express server listening on port %d in %s mode", 
   app.address().port, app.settings.env);
});

var nowjs = require("now");
var everyone = nowjs.initialize(app);
everyone.now.distributeMessage = function(message){
 everyone.now.receiveMessage(message);
};

It is not perfect, but it works fine. The core part is the callback for app.post -> ‘/api/photos’.
In the following blog, I will list brief client-side code.