Skip to content

What is Web.js? 什么是Web.js? 何がWeb.jsです?

iwillwen edited this page Jan 21, 2012 · 2 revisions

什么是webjs?

What is webjs?

何がwebjsです?

webjs是一个为Node.js而设计的Web开发框架。它可以帮助你快速在Node.js创建你的Web应用程序。 你可以使用它来写出更优雅的代码。 webjs is a web development framework. It can help you very fast to bulid a app on Node.js. You even only need to write less codes to achieve it.

Just like this:

//Node.js
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/');

//webjs
var web = require('webjs')
    .run(1337)
    .get({
        '/': function (req, res) {
            res.send('Hello World\n');
        }
    });
console.log('Server running at http://127.0.0.1:1337/');

如果你想用Node.js来创建一个公共文件服务器,并对文件夹结构进行隐藏,你可以使用地址映射的方式进行安全保护。 例如把用户请求的/2011/09/03/1.jpg文件映射到真正的/2011-09-03-1.jpg去。在Node.js中,你需要这样做: If you want to link '/2011/09/03/1.jpg' to '/2011-09-03-1.jpg'. You will do that in Node.js:

var http = require('http');
var fs = require('fs');
var url = require('url');
var pubRoot = __dirname + '/public';
http.createServer(function (req, res) {
    var pathname = url.parse(req.url).pathname;
    if (/\/(\d{4})\/(\d{2})\/(\d{2})\/(\d).jpg/.test(pathname)) {
        var filename = pathname.replace(/\/(\d{4})\/(\d{2})\/(\d{2})\/(\d).jpg/, '$1-$2-$3-$4.jpg');
        fs.readFile(pubRoot + filename, function (err, data) {
            if (err) {
                res.writeHead(404);
                res.end('Image not found.');
                return;
            }
            res.writeHead(200, {'Content-type': 'image/jpeg'});
            res.end(data);
        })
    }
}).listen(1337, "127.0.0.1");
console.log('Server running at http://127.0.0.1:1337/');

你可以通过webjs来简单实现它。 But if you use webjs to achieve it.

var web = require('webjs');
web.run(1337)
    .use(web.static(__dirname + '/public'))
.url({
        '/:year/:month/:day/:id.jpg': '(:year)-(:month)-(:day)-(:id).jpg'
    });
console.log('Server running at http://127.0.0.1:1337/');

这是webjs的UrlRouter特性,很酷吧。 This is webjs's Url Router, it's very cool!


如果你想通过Node.js创建一个想Google的goo.gl或者像Twitter的t.co,你需要如此。 Also you want to bulid a shorturl app for yourself, like goo.gl.

var http = require('http');
var url = require('url');
var fs = require('fs');
var router = {};
var shortcul = http.createServer(function (req, res) {
    switch (req.method) {
        case 'GET':
            var key = url.parse(req.url).pathname.substring(1);
            if (key in router) {
                res.writeHead(302, {'Location': router[key]});
                res.end();
                return;
            }
            fs.readFile('index.html', function (err, data) {
                res.writeHead(200, {'Content-type': 'text/html'});
                res.end(data);
            });
            break;
        case 'POST':
            var content = '';
            req.on('data', function (chunk) {
                    content += '';
                })
                .on('end', function () {
                    content = JSON.parse(content);
                    var key = Math.random().toString().substr(2),
                        urlInfo = url.parse(req.url);
                    router[key] = content.target;
                    res.writeHead(200, {'Content-type': 'text/plain'});
                    res.end(urlInfo.protocol + '//' + urlInfo.hostname + '/' + key);
                });
    }
});
shortcut.listen(80);

当然你也可以利用webjs非常简单的UrlRouter来实现它。 You can use webjs to achieve it.

var web = require('webjs');
var postRouter = {
    '/addUrl': function (req, res) {
        var _shortUrl = Math.random().toString().substr(2);
        web.url('/' + _shortUrl, req.data.url);
        res.send('http' + _shortUrl);
    }
};
web.run() //Default listen to 80 port
    .post(postRouter);

怎么样,不错吧。webjs还能做很多事情呢。


你也许会想给自己做一个TODO List,对webjs来说那是非常简单的。 You also wanna bulid a todos list for yourself, that's very easy to achieve it with webjs.

var web = require('webjs');
var mongo = require('mongoose');
var Schema = mongo.Schema;

web.run();
web.config({
    'db': 'mongo://localhost/todos',
    'mode': 'pro',
    'views': __dirname + '/views'
});

var doingItem = new Schema({
    content: String,
    finished: Boolean
});
var doingItems = mongo.model('doingItems', doingItem);
web.set(’doingItems‘, doingItems)     //web.set is the same to web.config
    .use(web.bodyParse());

var getRouter = {
    '/': function (req, res) {
        doingItems.find().toArray(function ( err, items ) {
            if (err) return res.sendError(500);
	res.render('index', { doingItems: items })
        });
    }
};
var postRouter = {
    '/addItem': function (req, res) {
        new doingItems({
            content: req.data.content,
            finished: false
        }).save(function (err) {
            if (err) return res.sendError(500);
            res.redirect('/');
        });
    }
};
web.get(getRouter)
    .post(postRouter);

webjs默认使用jade引擎来对页面进行渲染。 webjs default use jade to render the page.