NodeJS & Express: get URL image and refresh ALL linked screen (1)
Blogs20122012-06-01
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.
