• Archive by category "Javascript语言实践"
  • (Page 12)

Blog Archives

Socket.io在线聊天室

从零开始nodejs系列文章,将介绍如何利Javascript做为服务端脚本,通过Nodejs框架web开发。Nodejs框架是基于V8的引擎,是目前速度最快的Javascript引擎。chrome浏览器就基于V8,同时打开20-30个网页都很流畅。Nodejs标准的web开发框架Express,可以帮助我们迅速建立web站点,比起PHP的开发效率更高,而且学习曲线更低。非常适合小型网站,个性化网站,我们自己的Geek网站!!

关于作者

  • 张丹(Conan), 程序员Java,R,PHP,Javascript
  • weibo:@Conan_Z
  • blog: http://blog.fens.me
  • email: bsspirit@gmail.com

转载请注明出处:
http://blog.fens.me/nodejs-socketio-chat/

socketio

前言

网络聊天室在web1.0的时代就出现了,但当时技术支持比较有限,大都是通过浏览器插件BHO,JavaApplet,Flash实现的。如今HTML5技术风起云涌,通过websocket实现的网络聊天室,被定义为websocket的第一个实验,就像Hello World一样的简单。

今天我也动手完成了这个实验,感觉真的很爽!

目录

  1. socket.io介绍
  2. 服务器端和客户端通信设计
  3. 服务器端实现
  4. 客户端实现
  5. 完整案例代码

1. socket.io介绍

socket.io一个是基于Nodejs架构体系的,支持websocket的协议用于时时通信的一个软件包。socket.io 给跨浏览器构建实时应用提供了完整的封装,socket.io完全由javascript实现。

基于Nodejs实现webscoket其他的框架,请参考文章:Nodejs实现websocket的4种方式

2. 服务器端和客户端通信设计

chat

上图中client1 和 server 描述通信过程,client2描述对其他的客户端,通过广播进行消息通信。

  1. client1向server发起连接请求
  2. server接受client的连接
  3. client1输入登陆用户名
  4. server返回欢迎语
  5. server通过广播告诉其他在线的用户,client1已登陆
  6. client1发送聊天信息
  7. server返回聊天信息(可省略)
  8. server通过广播告诉其他在线的用户,client1的聊天消息
  9. client1关闭连接,退出登陆
  10. server通过广播告诉其他在线的用户,client1已退出

我们看一下测试截图:
chat2

  1. 左边: aaa 登陆
  2. 右边: bbb 登陆
  3. 左边: aaa 收到 bbb登陆欢迎消息
  4. aaa 和 bbb 实现对话
  5. 右边: bbb 刷新浏览自动退出
  6. 左边: aaa 收到 bbb的退出消息
  7. 右边: CCC 登陆
  8. 左边: aaa 收到 CCC 登陆欢迎消息
  9. aaa 和 CCC 实现对话

3. 服务器端实现

我们这里使用socket.io和express3的混合模式,让HTTP请求和WebSocket请求都使用3000端口。

服务器端实现,只有一个核心文件app.js。


//引入程序包
var express = require('express')
  , path = require('path')
  , app = express()
  , server = require('http').createServer(app)
  , io = require('socket.io').listen(server);

//设置日志级别
io.set('log level', 1); 

//WebSocket连接监听
io.on('connection', function (socket) {
  socket.emit('open');//通知客户端已连接

  // 打印握手信息
  // console.log(socket.handshake);

  // 构造客户端对象
  var client = {
    socket:socket,
    name:false,
    color:getColor()
  }

  // 对message事件的监听
  socket.on('message', function(msg){
    var obj = {time:getTime(),color:client.color};

    // 判断是不是第一次连接,以第一条消息作为用户名
    if(!client.name){
        client.name = msg;
        obj['text']=client.name;
        obj['author']='System';
        obj['type']='welcome';
        console.log(client.name + ' login');

        //返回欢迎语
        socket.emit('system',obj);
        //广播新用户已登陆
        socket.broadcast.emit('system',obj);
     }else{

        //如果不是第一次的连接,正常的聊天消息
        obj['text']=msg;
        obj['author']=client.name;      
        obj['type']='message';
        console.log(client.name + ' say: ' + msg);

        // 返回消息(可以省略)
        socket.emit('message',obj);
        // 广播向其他用户发消息
        socket.broadcast.emit('message',obj);
      }
    });

    //监听出退事件
    socket.on('disconnect', function () {  
      var obj = {
        time:getTime(),
        color:client.color,
        author:'System',
        text:client.name,
        type:'disconnect'
      };

      // 广播用户已退出
      socket.broadcast.emit('system',obj);
      console.log(client.name + 'Disconnect');
    });

});

//express基本配置
app.configure(function(){
  app.set('port', process.env.PORT || 3000);
  app.set('views', __dirname + '/views');
  app.use(express.favicon());
  app.use(express.logger('dev'));
  app.use(express.bodyParser());
  app.use(express.methodOverride());
  app.use(app.router);
  app.use(express.static(path.join(__dirname, 'public')));
});

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

// 指定webscoket的客户端的html文件
app.get('/', function(req, res){
  res.sendfile('views/chat.html');
});

server.listen(app.get('port'), function(){
  console.log("Express server listening on port " + app.get('port'));
});

var getTime=function(){
  var date = new Date();
  return date.getHours()+":"+date.getMinutes()+":"+date.getSeconds();
}

var getColor=function(){
  var colors = ['aliceblue','antiquewhite','aqua','aquamarine','pink','red','green',
                'orange','blue','blueviolet','brown','burlywood','cadetblue'];
  return colors[Math.round(Math.random() * 10000 % colors.length)];
}

4. 客户端实现

这里我们需要定义几个文件:chat.html, chat.js, jquery.min.js, main.css

1). views/chat.html


<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Socket.io - Simple chat</title>
<link rel="stylesheet" type="text/css" href="css/main.css">
<script src="javascripts/jquery.min.js"></script>
<script src="/socket.io/socket.io.js"></script>
<script src="javascripts/chat.js"></script>
</head>
<body>
<h1>Socket.io - Simple chat room</h1>
<div>
<span id="status">Connecting...</span>
<input type="text" id="input"/>
</div>
<div id="content"></div>
</body>
</html>

2). public/javascript/chat.js


$(function () {
var content = $('#content');
var status = $('#status');
var input = $('#input');
var myName = false;

//建立websocket连接
socket = io.connect('http://localhost:3000');
//收到server的连接确认
socket.on('open',function(){
status.text('Choose a name:');
});

//监听system事件,判断welcome或者disconnect,打印系统消息信息
socket.on('system',function(json){
var p = '';
if (json.type === 'welcome'){
if(myName==json.text) status.text(myName + ': ').css('color', json.color);
p = '<p style="background:'+json.color+'">system @ '+ json.time+ ' : Welcome ' + json.text +'</p>';
}else if(json.type == 'disconnect'){
p = '<p style="background:'+json.color+'">system @ '+ json.time+ ' : Bye ' + json.text +'</p>';
}
content.prepend(p);
});

//监听message事件,打印消息信息
socket.on('message',function(json){
var p = '<p><span style="color:'+json.color+';">' + json.author+'</span> @ '+ json.time+ ' : '+json.text+'</p>';
content.prepend(p);
});

//通过“回车”提交聊天信息
input.keydown(function(e) {
if (e.keyCode === 13) {
var msg = $(this).val();
if (!msg) return;
socket.send(msg);
$(this).val('');
if (myName === false) {
myName = msg;
}
}
});
});

3). public/javascript/jquery.min.js
从jquery官方下载: http://jquery.com/

4). public/css/main.css


* {padding:0px; margin:0px;}
body{font-family:tahoma; font-size:12px;margin:10px;}
p {line-height:18px;padding:2px;}
div {width:500px;}
#content { 
    padding:5px; 
    background:#ddd; 
    border-radius:5px;
    border:1px solid #CCC; 
    margin-top:10px; 
}
#input { 
    border-radius:2px; 
    border:1px solid #ccc;
    margin-top:10px; 
    padding:5px; 
    width:380px;  
}
#status { 
    width:100px; 
    display:block; 
    float:left; 
    margin-top:15px; 
}

5. 完整案例代码

项目已经上传到github: https://github.com/bsspirit/chat-websocket

下载,安装,启动服务器


git clone https://github.com/bsspirit/chat-websocket.git
npm install
node app.js

打开浏览器
可以多打开几个窗口,模拟不同用户有的对话。
http://localhost:3000

做完实验,感觉棒极了。技术创新的革命!!

转载请注明出处:
http://blog.fens.me/nodejs-socketio-chat/

打赏作者

Nodejs实现websocket的4种方式

从零开始nodejs系列文章,将介绍如何利Javascript做为服务端脚本,通过Nodejs框架web开发。Nodejs框架是基于V8的引擎,是目前速度最快的Javascript引擎。chrome浏览器就基于V8,同时打开20-30个网页都很流畅。Nodejs标准的web开发框架Express,可以帮助我们迅速建立web站点,比起PHP的开发效率更高,而且学习曲线更低。非常适合小型网站,个性化网站,我们自己的Geek网站!!

关于作者

  • 张丹(Conan), 程序员Java,R,PHP,Javascript
  • weibo:@Conan_Z
  • blog: http://blog.fens.me
  • email: bsspirit@gmail.com

转载请注明出处:
http://blog.fens.me/nodejs-websocket/

nodejs-websocket

前言

WebSocket是HTML5开始提供的一种浏览器与服务器间进行全双工通讯的网络技术。在WebSocket API中,浏览器和服务器只需要要做一个握手(handshaking)的动作,然后,浏览器和服务器之间就形成了一条快速通道。两者之间就直接可以数据互相传送。

WebSocket是一个通信的协议,分为服务器和客户端。服务器放在后台,保持与客户端的长连接,完成双方通信的任务。客户端一般都是实现在支持HTML5浏览器核心中,通过提供JavascriptAPI使用网页可以建立websocket连接。Java实现的案例,请参考:Java现实WebSocket

今天让我们来看看在nodejs中,如何实现websocket的通信。

目录

  1. 为什么用Nodejs
  2. node-websocket-server:测试失败
  3. node-websocket:测试成功
  4. faye-websocket-node: 测试成功
  5. socket.io: 测试成功
  6. 最后总结

1. 为什么用Nodejs?

1. 事件驱动,通过闭包很容易实现客户端的生命活期。
2. 不用担心多线程,锁,并行计算的问题
3. V8引擎速度非常快
4. 对于游戏来说,写一遍游戏逻辑代码,前端后端通用。

当然Nodejs也有一些缺点:
1. nodejs更新很快,可能会出现版本联兼容
2. nodejs还不算成熟,还没有大制作。
3. nodejs不像其他的服务器,对于不同的连接,不支持进程和线程操作。

在权衡Nodejs给我们带来无限畅快的开发的同时,要考虑到他的不成熟,特别是对于“长连接”的网络通信应用。下面我将分别,测试一下网上几种Nodejs实现websocket的框架。

我的系统环境

  • win7 64bit
  • Nodejs:v0.10.5
  • Npm:1.2.19
~ D:\workspace\javascript>node -v
v0.10.5

~ D:\workspace\javascript>npm -v
1.2.19

2. node-websocket-server: 测试失败

github: https://github.com/miksago/node-websocket-server
node-websocket-server:是基于nodejs底层API实现的,可能产生不兼容的机率是90-100%,现在已经不建议再使用了。我查了代码库,发现已经有两年没有更新了,所以还在准备用node-websocket-server框架的同学,要特别小心了。

我也做了一个实验,一直会报错,贴一下实验代码。


~ D:\workspace\javascript>mkdir nodejs-websocket-server
~ D:\workspace\javascript>cd nodejs-websocket-server
~ D:\workspace\javascript\nodejs-websocket-server>npm install websocket-server
npm http GET https://registry.npmjs.org/websocket-server
npm http 304 https://registry.npmjs.org/websocket-server
npm http GET https://registry.npmjs.org/websocket-server/-/websocket-server-1.4.04.tgz
npm http 200 https://registry.npmjs.org/websocket-server/-/websocket-server-1.4.04.tgz
websocket-server@1.4.04 node_modules\websocket-server

~ vi app.js
var conns = new Array();

var ws = require("websocket-server");
var server = ws.createServer();

server.addListener("connection", function(connection){
  console.log("Connection request on Websocket-Server");
  conns.push(connection);
  connection.addListener('message',function(msg){
        console.log(msg);
        for(var i=0; i<conns.length; i++){
            if(conns[i]!=connection){
                conns[i].send(msg);
            }
        }
    });
});
server.listen(3001);

客户端连接:


<html>
<body>
<div id="output"></div>
<script>
function checkBrowser(){
if (window.WebSocket){
log("This browser supports WebSocket!");
} else {
log("This browser does not support WebSocket.");
}
}
function setup(){
var wsServer = 'ws://localhost:3001';
var ws = new WebSocket(wsServer);

ws.onopen = function (e) {
log("Connected to WebSocket server.",e);
sendMessage("Conan");
} ;

ws.onclose = function (e) {
log("Disconnected",e);
} ;

ws.onmessage = function(e) {
log("RECEIVED: " + e.data, e);
ws.close();
}

ws.onerror = function (e) {
log('Error occured: ' + e.data,e);
} ;

var sendMessage = function(msg){
ws.send(msg);
log("SEND : "+ msg);
}
}

function log(s,e) {
var output = document.getElementById("output");
var p = document.createElement("p");
p.style.wordWrap = "break-word";
p.style.padding="10px";
p.style.background="#eee";
p.textContent = "LOG : "+s;
output.appendChild(p);
console.log("LOG : "+s, e);
}

checkBrowser();
setup();
</script>
</body>
</html>

错误提示:
ws-error

查了一下原因,node-websocket-server,不支持websocket的draft-10,而chrome 14+浏览器,只支持draft-10的websocket,这样chrome基本都不能用了。我的chrome版本是28.0.1500.95。所以,大家就换个思路吧!

3. WebSocket-Node: 测试成功

github: https://github.com/Worlize/WebSocket-Node
WebSocket-Node,是一个简单的库,不仅支持draft-10,还有之前的各种版本。

服务器端配置


~ D:\workspace\javascript>mkdir nodejs-websocket
~ D:\workspace\javascript>cd nodejs-websocket
D:\workspace\javascript\nodejs-websocket>npm install websocket
npm http GET https://registry.npmjs.org/websocket
npm http 304 https://registry.npmjs.org/websocket

> websocket@1.0.8 install D:\workspace\javascript\nodejs-websocket\node_modules\websocket
> node install.js

[websocket v1.0.8] Attempting to compile native extensions.
[websocket v1.0.8]
    Native code compile failed!!
    Please note that this module DOES NOT REQUIRE the native components
    and will still work without them, though not quite as efficiently.

    On Windows, native extensions require Visual Studio and Python.
    On Unix, native extensions require Python, make and a C++ compiler.
    Start npm with --websocket:verbose to show compilation output (if any).
websocket@1.0.8 node_modules\websocket

上面提示有错误,我本机已经装了Visual Studio和Python,看来有些模块本地编译不成功了。

增加app.js


~ vi app.js

// http://ejohn.org/blog/ecmascript-5-strict-mode-json-and-more/
"use strict";

// Optional. You will see this name in eg. 'ps' or 'top' command
process.title = 'node-chat';

// Port where we'll run the websocket server
var webSocketsServerPort = 3001;

// websocket and http servers
var webSocketServer = require('websocket').server;
var http = require('http');

/**
 * Global variables
 */
// latest 100 messages
var history = [ ];
// list of currently connected clients (users)
var clients = [ ];

/**
 * Helper function for escaping input strings
 */
function htmlEntities(str) {
    return String(str).replace(/&/g, '&').replace(/>/g, '>').replace(/"/g, '"');
}

// Array with some colors
var colors = [ 'red', 'green', 'blue', 'magenta', 'purple', 'plum', 'orange' ];
// ... in random order
colors.sort(function(a,b) { return Math.random() > 0.5; } );

/**
 * HTTP server
 */
var server = http.createServer(function(request, response) {
    // Not important for us. We're writing WebSocket server, not HTTP server
});
server.listen(webSocketsServerPort, function() {
    console.log((new Date()) + " Server is listening on port " + webSocketsServerPort);
});

/**
 * WebSocket server
 */
var wsServer = new webSocketServer({
    // WebSocket server is tied to a HTTP server. WebSocket request is just
    // an enhanced HTTP request. For more info http://tools.ietf.org/html/rfc6455#page-6
    httpServer: server
});

// This callback function is called every time someone
// tries to connect to the WebSocket server
wsServer.on('request', function(request) {
    console.log((new Date()) + ' Connection from origin ' + request.origin + '.');

    // accept connection - you should check 'request.origin' to make sure that
    // client is connecting from your website
    // (http://en.wikipedia.org/wiki/Same_origin_policy)
    var connection = request.accept(null, request.origin); 
    // we need to know client index to remove them on 'close' event
    var index = clients.push(connection) - 1;
    var userName = false;
    var userColor = false;

    console.log((new Date()) + ' Connection accepted.');

    // send back chat history
    if (history.length > 0) {
        connection.sendUTF(JSON.stringify( { type: 'history', data: history} ));
    }

    // user sent some message
    connection.on('message', function(message) {
        if (message.type === 'utf8') { // accept only text
            if (userName === false) { // first message sent by user is their name
                // remember user name
                userName = htmlEntities(message.utf8Data);
                // get random color and send it back to the user
                userColor = colors.shift();
                connection.sendUTF(JSON.stringify({ type:'color', data: userColor }));
                console.log((new Date()) + ' User is known as: ' + userName
                            + ' with ' + userColor + ' color.');

            } else { // log and broadcast the message
                console.log((new Date()) + ' Received Message from '
                            + userName + ': ' + message.utf8Data);

                // we want to keep history of all sent messages
                var obj = {
                    time: (new Date()).getTime(),
                    text: htmlEntities(message.utf8Data),
                    author: userName,
                    color: userColor
                };
                history.push(obj);
                history = history.slice(-100);

                // broadcast message to all connected clients
                var json = JSON.stringify({ type:'message', data: obj });
                for (var i=0; i < clients.length; i++) {
                    clients[i].sendUTF(json);
                }
            }
        }
    });

    // user disconnected
    connection.on('close', function(connection) {
        if (userName !== false && userColor !== false) {
            console.log((new Date()) + " Peer "
                + connection.remoteAddress + " disconnected.");
            // remove user from the list of connected clients
            clients.splice(index, 1);
            // push back user's color to be reused by another user
            colors.push(userColor);
        }
    });

});

启动服务器


~ D:\workspace\javascript\nodejs-websocket>node app.js
Warning: Native modules not compiled.  XOR performance will be degraded.
Warning: Native modules not compiled.  UTF-8 validation disabled.
Wed Aug 21 2013 15:28:48 GMT+0800 (中国标准时间) Server is listening on port 3001
Wed Aug 21 2013 15:28:53 GMT+0800 (中国标准时间) Connection from origin null.
Wed Aug 21 2013 15:28:53 GMT+0800 (中国标准时间) Connection accepted.
Wed Aug 21 2013 15:28:53 GMT+0800 (中国标准时间) User is known as: Conan with red color.
Wed Aug 21 2013 15:28:53 GMT+0800 (中国标准时间) Peer undefined disconnected.

我们看到XOR 和UTF-8 validation 两个模块是被禁止的,不过不影响测试。

客户端,还是使用一样的。

ws-client1

另外,WebSocket-Node还提供C/S模式的交互,可以不使用浏览器

服务端代码


~ vi app2.js

#!/usr/bin/env node
var WebSocketServer = require('websocket').server;
var http = require('http');

var server = http.createServer(function(request, response) {
    console.log((new Date()) + ' Received request for ' + request.url);
    response.writeHead(404);
    response.end();
});
server.listen(3001, function() {
    console.log((new Date()) + ' Server is listening on port 3001');
});

wsServer = new WebSocketServer({
    httpServer: server,
    // You should not use autoAcceptConnections for production
    // applications, as it defeats all standard cross-origin protection
    // facilities built into the protocol and the browser.  You should
    // *always* verify the connection's origin and decide whether or not
    // to accept it.
    autoAcceptConnections: false
});

function originIsAllowed(origin) {
  // put logic here to detect whether the specified origin is allowed.
  return true;
}

wsServer.on('request', function(request) {
    if (!originIsAllowed(request.origin)) {
      // Make sure we only accept requests from an allowed origin
      request.reject();
      console.log((new Date()) + ' Connection from origin ' + request.origin + ' rejected.');
      return;
    }

    var connection = request.accept('echo-protocol', request.origin);
    console.log((new Date()) + ' Connection accepted.');
    connection.on('message', function(message) {
        if (message.type === 'utf8') {
            console.log('Received Message: ' + message.utf8Data);
            connection.sendUTF(message.utf8Data);
        }
        else if (message.type === 'binary') {
            console.log('Received Binary Message of ' + message.binaryData.length + ' bytes');
            connection.sendBytes(message.binaryData);
        }
    });
    connection.on('close', function(reasonCode, description) {
        console.log((new Date()) + ' Peer ' + connection.remoteAddress + ' disconnected.');
    });
});

客户端代码


~ vi client.js

#!/usr/bin/env node
var WebSocketClient = require('websocket').client;

var client = new WebSocketClient();

client.on('connectFailed', function(error) {
    console.log('Connect Error: ' + error.toString());
});

client.on('connect', function(connection) {
    console.log('WebSocket client connected');
    connection.on('error', function(error) {
        console.log("Connection Error: " + error.toString());
    });
    connection.on('close', function() {
        console.log('echo-protocol Connection Closed');
    });
    connection.on('message', function(message) {
        if (message.type === 'utf8') {
            console.log("Received: '" + message.utf8Data + "'");
        }
    });

    function sendNumber() {
        if (connection.connected) {
            var number = Math.round(Math.random() * 0xFFFFFF);
            connection.sendUTF(number.toString());
            setTimeout(sendNumber, 1000);
        }
    }
    sendNumber();
});

client.connect('ws://localhost:3001/', 'echo-protocol');

程序启动:


~ D:\workspace\javascript\nodejs-websocket>node app2.js
~ D:\workspace\javascript\nodejs-websocket>node client.js

ws-node

测试成功!!

4. faye-websocket-node: 测试成功

github: https://github.com/faye/faye-websocket-node
faye-websocket-node,是扩展faye项目而开发的websocket的一个实现。

服务器端配置


~ D:\workspace\javascript>mkdir nodejs-faye-websocket
~ D:\workspace\javascript>cd nodejs-faye-websocket
~ D:\workspace\javascript\nodejs-faye-websocket>npm install faye-websocket
npm http GET https://registry.npmjs.org/faye-websocket
npm http 304 https://registry.npmjs.org/faye-websocket
npm http GET https://registry.npmjs.org/faye-websocket/-/faye-websocket-0.6.1.tgz
npm http 200 https://registry.npmjs.org/faye-websocket/-/faye-websocket-0.6.1.tgz
npm http GET https://registry.npmjs.org/websocket-driver
npm http 200 https://registry.npmjs.org/websocket-driver
npm http GET https://registry.npmjs.org/websocket-driver/-/websocket-driver-0.2.2.tgz
npm http 200 https://registry.npmjs.org/websocket-driver/-/websocket-driver-0.2.2.tgz
faye-websocket@0.6.1 node_modules\faye-websocket
└── websocket-driver@0.2.2

~ vi app.js
var WebSocket = require('faye-websocket'),
    http      = require('http');

var server = http.createServer();

server.on('upgrade', function(request, socket, body) {
  if (WebSocket.isWebSocket(request)) {
    var ws = new WebSocket(request, socket, body);

    ws.on('message', function(event) {
      ws.send(event.data);
    });

    ws.on('close', function(event) {
      console.log('close', event.code, event.reason);
      ws = null;
    });
  }
});

server.listen(3001);

~ D:\workspace\javascript\nodejs-faye-websocket>node app.js

用网页客户端访问:

ws-faye

测试成功,非常简单!!而且,没有依赖其他的库!!

5. socket.io: 测试成功

github: https://github.com/LearnBoost/socket.io

环境配置


~ D:\workspace\javascript>express -e nodejs-socketio
~ D:\workspace\javascript>cd nodejs-socketio && npm install
~ D:\workspace\javascript\nodejs-socketio>npm install socket.io

修改app.js配置文件


~ vi app.js

var app = require('express')()
  , server = require('http').createServer(app)
  , io = require('socket.io').listen(server);

server.listen(80);

app.get('/', function (req, res) {
  res.sendfile(__dirname + '/client/index.html');
});

io.sockets.on('connection', function (socket) {
  socket.emit('news', { hello: 'world' });
  socket.on('my other event', function (data) {
    console.log(data);
  });
});

增加客户端文件,注意这个的index.html要根据app.js指定的位置”res.sendfile(__dirname + ‘/client/index.html’);”


~ mkdir client
~ vi /client/index.html

<!DOCTYPE html>
<html>
<head>
<title>socket.io</title>
<link rel='stylesheet' href='/stylesheets/style.css' />
</head>
<body>
<h1>socket.io</h1>
<p>Welcome to socket.io</p>

<script src="/socket.io/socket.io.js"></script>
<script>
var socket = io.connect('http://localhost');
socket.on('news', function (data) {
console.log(data);
socket.emit('my other event', { my: 'data' });
});
</script>
</body>
</html>

启动服务器


~ D:\workspace\javascript\nodejs-socketio>node app.js
   info  - socket.io started

打开浏览器: http://localhost
ws-socketio

查看服务器日志:


  debug - served static content /socket.io.js
   debug - client authorized
   info  - handshake authorized ZR-xQhsKCCqM03TRHW4b
   debug - setting request GET /socket.io/1/websocket/ZR-xQhsKCCqM03TRHW4b
   debug - set heartbeat interval for client ZR-xQhsKCCqM03TRHW4b
   debug - client authorized for
   debug - websocket writing 1::
   debug - websocket writing 5:::{"name":"news","args":[{"hello":"world"}]}
{ my: 'data' }
   debug - emitting heartbeat for client ZR-xQhsKCCqM03TRHW4b
   debug - websocket writing 2::
   debug - set heartbeat timeout for client ZR-xQhsKCCqM03TRHW4b
   debug - got heartbeat packet
   debug - cleared heartbeat timeout for client ZR-xQhsKCCqM03TRHW4b
   debug - set heartbeat interval for client ZR-xQhsKCCqM03TRHW4b

测试成功。

6. 最后总结

今天尝试了4种,基于nodejs的websocket的框架。

  • node-websocket-server:是直接放弃的。
  • node-websocket:需要依赖于底层的C++,Python的环境,支持以node做客户端的访问。
  • faye-websocket-node:是faye软件框架体系的一部分,安装简单,不需要其他依赖库。
  • socket.io:功能强大,支持集成websocket服务器端和Express3框架与一身。

websocket我也是初次尝试,对于开发效率,代码结构,稳定性,服务器性能都需要做更多的测试。目前还无法定论,哪个框架是最好的,不过我比较看好socket.io和faye-websocket-node的未来前景。

转载请注明出处:
http://blog.fens.me/nodejs-websocket/

打赏作者

Yeoman自动构建js项目

从零开始nodejs系列文章,将介绍如何利Javascript做为服务端脚本,通过Nodejs框架web开发。Nodejs框架是基于V8的引擎,是目前速度最快的Javascript引擎。chrome浏览器就基于V8,同时打开20-30个网页都很流畅。Nodejs标准的web开发框架Express,可以帮助我们迅速建立web站点,比起PHP的开发效率更高,而且学习曲线更低。非常适合小型网站,个性化网站,我们自己的Geek网站!!

关于作者

  • 张丹(Conan), 程序员Java,R,PHP,Javascript
  • weibo:@Conan_Z
  • blog: http://blog.fens.me
  • email: bsspirit@gmail.com

转载请注明出处:
http://blog.fens.me/nodejs-yeoman-intro/
yeoman

前言
有一种技术可以提高我们的工作效率,可以让我们专心做我们擅长的事,可以屏蔽复杂性,可以规范我们的架构和我们的代码,可以让我们的享受编程的乐趣。Yeoman可以做到。

很多年以前,rails刚刚出世,伴随着一个新的名词“脚手架(scaffolding)”出现了。脚手架是一种提高开发效率的工具的代名词。随后,各种编程语言都开始实现自己的“脚手架”工具。Maven重新构造了Java的世界,改变了几千万的开发者对于Java项目构建的认识。Yeoman在Javascript领域正做着同样的事情。

看着各种工具,各种语言,都在飞跃式的进化。做为一个开发者,我每天都在为变化而惊喜!

目录

  1. Yeoman介绍
  2. Yeoman工具包yo命令
  3. Yeoman工具包yo – 快速构建一个web项目
  4. Yeoman工具包bower,grunt的组合用法

1. Yeoman介绍

Yeoman是Google的团队和外部贡献者团队合作开发的,他的目标是通过Grunt(一个用于开发任务自动化的命令行工具)和Bower(一个HTML、CSS、Javascript和图片等前端资源的包管理器)的包装为开发者创建一个易用的工作流。

Yeoman主要有三部分组成:yo(脚手架工具)、grunt(构建工具)、bower(包管理器)。这三个工具是分别独立开发的,但是需要配合使用,来实现我们高效的工作流模式。

2. Yeoman工具包yo命令

yo插件都是通过npm, Node.js包管理器安装和管理的.

我的系统环境

  • win7 64bit
  • Nodejs:v0.10.5
  • Npm:1.2.19
~ D:\workspace\javascript>node -v
v0.10.5

~ D:\workspace\javascript>npm -v
1.2.19

在系统中,我们已经安装好了Nodejs和npm。win7安装nodejs请参考文章:Nodejs开发框架Express3.0开发手记–从零开始

全局安装yo

~ D:\workspace\javascript>npm install -g yo

如果你还没有安装grunt,bower,也需要一起安装

~ D:\workspace\javascript>npm install -g grunt-cli bower

接下我们看一下yo命令行操作
1). 通过help查看帮助


~ D:\workspace\javascript>yo --help
Yeoman is a mask worn by the following members of the open-source community:

  Paul Irish, Addy Osmani, Mickael Daniel, Sindre Sorhus, Eric Bidelman,
  Frederick Ros, Brian Ford, Pascal Hartig, Stephen Sawchuk, and countless
  other contributors.

Usage: yo GENERATOR [args] [options]

General options:
  -h, --help     # Print generator's options and usage
  -f, --force    # Overwrite files that already exist

Please choose a generator below.
Angular
  angular:app
  angular:common
  angular:constant
  angular:controller
  angular:decorator
  angular:directive
  angular:factory
  angular:filter
  angular:main
  angular:provider
  angular:route
  angular:service
  angular:value
  angular:view

Karma
  karma:app

Mocha
  mocha:app
  mocha:generator

Webapp
  webapp:app

yo的命令很简单:yo GENERATOR,例如:yo webapp, yo angular
Please choose a generator below: 下面列出了我的系统中,已经安装的generator的库,例如:Angular,Karma,Mocha,Webapp

2). 查询yo的支持库


~ D:\workspace\javascript>yo
Yeoman is a mask worn by the following members of the open-source community:

  Paul Irish, Addy Osmani, Mickael Daniel, Sindre Sorhus, Eric Bidelman,
  Frederick Ros, Brian Ford, Pascal Hartig, Stephen Sawchuk, and countless
  other contributors.

[?] What would you like to do? (Use arrow keys)
 > Install a generator
   Find some help
   Get me out of here!

命令行会提示,我们想要的操作。这里选择”Install a generator”


[?] What would you like to do? Install a generator
[?] Search NPM for generators:web

系统继续提示,我们要查找的包,我们输入web

3). 安装generator-webapp库


[?] Here's what I found. Install one? (Use arrow keys)
 > generator-armadillo
   generator-bones
   generator-btapp
   generator-fe
   generator-flight
   generator-hazdev-webapp
   generator-hbswebapp
   generator-html5-site
   generator-jing
   generator-lessapp
   generator-nodestrap
   generator-sails
   generator-server-configs
   generator-starter
   generator-starttter
   generator-ultimate
   generator-webapp
   generator-webapp-bfytw
   generator-webapp-fintan
   generator-weblog
   generator-website
   Search again
   Return home

yo列出了,所有在官方已经注册的,web关键字相关的包,我们选择“generator-webapp”

yo通过npm开始下载generator-webapp安装包


[?] What would you like to do? Install a generator
[?] Search NPM for generators: web
[?] Here's what I found. Install one? generator-webapp

generator-webapp@0.2.7 D:\toolkit\nodejs\node_modules\generator-webapp
├── cheerio@0.12.1 (entities@0.3.0, underscore@1.4.4, htmlparser2@3.1.4, cheerio-select@0.0.3)
└── yeoman-generator@0.12.3 (dargs@0.1.0, diff@1.0.5, debug@0.7.2, async@0.2.9, mime@1.2.11, mkdirp@0.3.5, isbinaryfi
le@0.1.9, underscore.string@2.3.3, shelljs@0.1.4, iconv-lite@0.2.11, lodash@1.3.1, rimraf@2.1.4, nopt@2.1.2, cli-table@0
.2.0, tar@0.1.18, glob@3.2.6, inquirer@0.2.4, request@2.21.0)

I just installed your generator by running:
    npm install -g generator-webapp

然后,我们退出yo命令行,选择“Get me out of here!”


[?] What would you like to do? Get me out of here!

Bye from us! Chat soon.
            Addy Osmani
          Sindre Sorhus
        Brian Ford
     Eric Bidelman
              Paul Irish
     Mickael Daniel
          Pasca1 Hartig
      Stephen S.wchuk
    Frederick R0s

上面的退出的文字是开发者的名字,很有意思一点是,竖着看最中间一行的文字排列是,yeoman1.0,也就是yeoman这个项目的得名了。

4). 注:上面的过程,也可以直接用命令

npm install -g generator-webapp

3. Yeoman工具包yo – 快速构建一个web项目

当我们安装了generator-webapp后,我们就可以,以非常优雅的方式来构建工程了。

1). 创建nodejs-yo目录,并构建webapp工程


~ D:\workspace\javascript>mkdir nodejs-yo
~ D:\workspace\javascript>cd nodejs-yo
~ D:\workspace\javascript\nodejs-yo>yo webapp

     _-----_
    |       |
    |--(o)--|   .--------------------------.
   `---------´  |    Welcome to Yeoman,    |
    ( _´U`_ )   |   ladies and gentlemen!  |
    /___A___\   '__________________________'
     |  ~  |
   __'.___.'__
 ´   `  |° ´ Y `

Out of the box I include HTML5 Boilerplate, jQuery and Modernizr.
[?] What more would you like?
  [ ] Twitter Bootstrap for Sass
 >[X] RequireJS
  [X] Autoprefixer for your CSS

对选项的解释:

  • Twitter Bootstrap for Sass:SASS是一种CSS的开发工具,提供了许多便利的写法,大大节省了设计者的时间,使得CSS的开发,变得简单和可维护。
  • RequireJS 可以帮助用户异步按需的加载 JavaScript 代码,并解决 JavaScript 模块间的依赖关系,提升了前端代码的整体质量和性能。
  • Autoprefixer解析CSS文件并且添加浏览器前缀到CSS规则里,使用Can I Use的数据来决定哪些前缀是需要的。

上面3个选择,由于Sass是基于Ruby的,我本机没有安装ruby,取消Twitter Bootstrap for Sass的勾选。

2). 查看安装日志:


Out of the box I include HTML5 Boilerplate, jQuery and Modernizr.
[?] What more would you like? RequireJS, Autoprefixer for your CSS
   create Gruntfile.js
   create package.json
   create .gitignore
   create .gitattributes
   create .bowerrc
   create bower.json
   create .jshintrc
   create .editorconfig
   create app/favicon.ico
   create app/404.html
   create app/robots.txt
   create app/.htaccess
   create app/styles/main.css
   create app/scripts/app.js
   create app/scripts/main.js
   create app/index.html
   create app/scripts/hello.coffee
   invoke   mocha:app
   create     test\index.html
   create     test\lib\chai.js
   create     test\lib\expect.js
   create     test\lib\mocha\mocha.css
   create     test\lib\mocha\mocha.js
   create     test\spec\test.js

I'm all done. Running bower install & npm install for you to install the required dependencies. If this fails, try running the command yourself.

项目骨架已经建好了。还包括了很多的配置文件.gitignore,bower.json,Gruntfile.js,favicon.ico, robots.txt, .htaccess。太神奇了,Cool!!

一下子装备都齐全了,打仗的事就交给我们自己吧。

4. Yeoman工具包bower,grunt的组合用法

有关bower的介绍,请参考:bower解决js的依赖管理
有关grunt的介绍,请参考:grunt让Nodejs规范起来

1). 使用bower命令查看项目依赖:


~ D:\workspace\javascript\nodejs-yo>bower list
bower check-new     Checking for new versions of the project dependencies..
nodejs-yo#0.0.0 D:\workspace\javascript\nodejs-yo
├── jquery#1.9.1 (latest is 2.0.3)
├── modernizr#2.6.2
└── requirejs#2.1.8

我们发现生成的webapp中,有4个依赖库,jquery,modernizr,requirejs。

2). 使用grunt命令执行单元测试


D:\workspace\javascript\nodejs-yo>grunt test
Running "clean:server" (clean) task
Cleaning ".tmp"...OK

Running "concurrent:test" (concurrent) task

Running "copy:styles" (copy) task

Running "coffee:dist" (coffee) task

Running "autoprefixer:dist" (autoprefixer) task
File ".tmp/styles/main.css" created.

Running "connect:test" (connect) task
Starting connect web server on localhost:9000.

Running "mocha:all" (mocha) task
Testing: http://localhost:9000/index.html

  .

  1 test complete (107 ms)

>> 1 passed! (0.11s)

Done, without errors.

3). 使用grunt命令启动一个node服务器


~ D:\workspace\javascript\nodejs-yo>grunt server
Running "server" task

Running "clean:server" (clean) task

Running "concurrent:server" (concurrent) task
    Warning: Running "compass:dist" (compass) task
Warning: You need to have Ruby and Compass installed and in your system PATH for this task to work. More info: https://g
ithub.com/gruntjs/grunt-contrib-compass Use --force to continue. Use --force to continue.

    Aborted due to warnings.

启动时,我们发现报错了。由于我没有装Ruby的环境,所以compass:dist的命令不能运行。

强制启动grunt


~ D:\workspace\javascript\nodejs-yo>grunt server --force
D:\workspace\javascript\nodejs-yo>grunt server --force
Running "server" task

Running "clean:server" (clean) task
Cleaning ".tmp"...OK

Running "concurrent:server" (concurrent) task

Running "coffee:dist" (coffee) task
    Warning: Running "compass:dist" (compass) task
Warning: You need to have Ruby and Compass installed and in your system PATH for this task to work. More info: https://
ithub.com/gruntjs/grunt-contrib-compass Use --force to continue. Used --force, continuing.

Running "compass:dist" (compass) task
Warning: You need to have Ruby and Compass installed and in your system PATH for this task to work. More info: https://
ithub.com/gruntjs/grunt-contrib-compass Use --force to continue.

Running "copy:styles" (copy) task

Running "autoprefixer:dist" (autoprefixer) task
File ".tmp/styles/main.css" created.

Running "connect:livereload" (connect) task
Starting connect web server on localhost:9000.

Running "open:server" (open) task

Running "watch" task
Waiting...

后台日志显示了“watch”的task,说明代码文件被监控着,如有修改网页会自动更新。

浏览器被自动打开,http://localhost:9000/
yeoman1

4). 修改app/index.html代码,增加对canvas的检查。


~ vi app/index.html

<script>
window.onload = function () {
if (canvasSupported()) {
alert('canvas supported');
}
};

function canvasSupported() {
var canvas = document.createElement('canvas');
return (canvas.getContext && canvas.getContext('2d'));
}
</script>

浏览器显示:
yeoman2

5). 通过bower增加库jquery-pjax


~ D:\workspace\javascript\nodejs-yo>bower install jquery-pjax
bower jquery-pjax#*         not-cached git://github.com/defunkt/jquery-pjax.git#*
bower jquery-pjax#*            resolve git://github.com/defunkt/jquery-pjax.git#*
bower jquery-pjax#*           download https://github.com/defunkt/jquery-pjax/archive/v1.7.3.tar.gz
bower jquery-pjax#*            extract archive.tar.gz
bower jquery-pjax#*           resolved git://github.com/defunkt/jquery-pjax.git#1.7.3
bower jquery#>=1.8              cached git://github.com/components/jquery.git#2.0.3
bower jquery#>=1.8            validate 2.0.3 against git://github.com/components/jquery.git#>=1.8
bower jquery-pjax#~1.7.3       install jquery-pjax#1.7.3

jquery-pjax#1.7.3 app\bower_components\jquery-pjax
└── jquery#2.0.3

~ D:\workspace\javascript\nodejs-yo>bower list
bower check-new     Checking for new versions of the project dependencies..
nodejs-yo#0.0.0 D:\workspace\javascript\nodejs-yo
├── jquery#1.9.1 (latest is 2.0.3)
├─┬ jquery-pjax#1.7.3 extraneous
│ └── jquery#1.9.1 (2.0.3 available)
├── modernizr#2.6.2
└── requirejs#2.1.8

Yeoman已经成功地帮助我们打造出一个项目的原型了,接下来我们可以针对自己的项目,自己熟悉的框架组合,构建一个属于自己的骨架模板,并发布到Yeoman的generator库中。

后面的内容会更精彩,敬请期待…!!

转载请注明出处:
http://blog.fens.me/nodejs-yeoman-intro/

打赏作者

bower解决js的依赖管理

从零开始nodejs系列文章,将介绍如何利Javascript做为服务端脚本,通过Nodejs框架web开发。Nodejs框架是基于V8的引擎,是目前速度最快的Javascript引擎。chrome浏览器就基于V8,同时打开20-30个网页都很流畅。Nodejs标准的web开发框架Express,可以帮助我们迅速建立web站点,比起PHP的开发效率更高,而且学习曲线更低。非常适合小型网站,个性化网站,我们自己的Geek网站!!

关于作者

  • 张丹(Conan), 程序员Java,R,PHP,Javascript
  • weibo:@Conan_Z
  • blog: http://blog.fens.me
  • email: bsspirit@gmail.com

转载请注明出处:
http://blog.fens.me/nodejs-bower-intro/

bower

前言
一个新的web项目开始,我们总是很自然地去下载需要用到的js类库文件,比如jQuery,去官网下载名为jquery-1.10.2.min.js文件,放到我们的项目里。当项目又需要bootstrap的时候,我们会重复刚才的工作,去bootstrap官网下载对应的类库。如果bootstrap所依赖的jQuery并不是1.10.2,而是2.0.3时,我们会再重新下载一个对应版本的jQuery替换原来的。

包管理是个复杂的问题,我们要知道谁依赖谁,还要明确哪个版本依赖哪个版本。这些对于开发人员来说,负担过重了。bower作为一个js依赖管理的工具,提供一种理想包管理方式,借助了npm的一些思想,为我们提供一个舒服的开发环境。

你要还不动起手来试试bower,那你一定不会知道,前端开发是件多么享受的事。

目录

  1. bower介绍
  2. bower安装
  3. bower命令
  4. bower使用
  5. 用bower提交自己类库

1. bower介绍

Bower 是 twitter 推出的一款包管理工具,基于nodejs的模块化思想,把功能分散到各个模块中,让模块和模块之间存在联系,通过 Bower 来管理模块间的这种联系。

包管理工具一般有以下的功能:

  • 注册机制:每个包需要确定一个唯一的 ID 使得搜索和下载的时候能够正确匹配,所以包管理工具需要维护注册信息,可以依赖其他平台。
  • 文件存储:确定文件存放的位置,下载的时候可以找到,当然这个地址在网络上是可访问的。
  • 上传下载:这是工具的主要功能,能提高包使用的便利性。比如想用 jquery 只需要 install 一下就可以了,不用到处找下载。上传并不是必备的,根据文件存储的位置而定,但需要有一定的机制保障。
  • 依赖分析:这也是包管理工具主要解决的问题之一,既然包之间是有联系的,那么下载的时候就需要处理他们之间的依赖。下载一个包的时候也需要下载依赖的包。

功能介绍,摘自文章:http://chuo.me/2013/02/twitter-bower.html

2. bower安装

bower插件是通过npm, Node.js包管理器安装和管理的.

我的系统环境

  • win7 64bit
  • Nodejs:v0.10.5
  • Npm:1.2.19
~ D:\workspace\javascript>node -v
v0.10.5

~ D:\workspace\javascript>npm -v
1.2.19

在系统中,我们已经安装好了Nodejs和npm。win7安装nodejs请参考文章:Nodejs开发框架Express3.0开发手记–从零开始

安装bower
全局安装bower


~ D:\workspace\javascript>npm install bower -g

新建一个express3的项目nodejs-bower


~ D:\workspace\javascript>express -e nodejs-bower
~ D:\workspace\javascript>cd nodejs-bower && npm install

3. bower命令

bower安装后,我们就可以用bower这个命令了。

~ D:\workspace\javascript\nodejs-bower>bower
Usage:
    bower  [] []
Commands:
    cache                   Manage bower cache
    help                    Display help information about Bower
    home                    Opens a package homepage into your favorite browser
    info                    Info of a particular package
    init                    Interactively create a bower.json file
    install                 Install a package locally
    link                    Symlink a package folder
    list                    List local packages
    lookup                  Look up a package URL by name
    prune                   Removes local extraneous packages
    register                Register a package
    search                  Search for a package by name
    update                  Update a local package
    uninstall               Remove a local package
Options:
    -f, --force             Makes various commands more forceful
    -j, --json              Output consumable JSON
    -l, --log-level         What level of logs to report
    -o, --offline           Do not hit the network
    -q, --quiet             Only output important information
    -s, --silent            Do not output anything, besides errors
    -V, --verbose           Makes output more verbose
    --allow-root            Allows running commands as root
See 'bower help ' for more information on a specific command.

Commands,列出了bower支持的各种命令。

  • cache:bower缓存管理
  • help:显示Bower命令的帮助信息
  • home:通过浏览器打开一个包的github发布页
  • info:查看包的信息
  • init:创建bower.json文件
  • install:安装包到项目
  • link:在本地bower库建立一个项目链接
  • list:列出项目已安装的包
  • lookup:根据包名查询包的URL
  • prune:删除项目无关的包
  • register:注册一个包
  • search:搜索包
  • update:更新项目的包
  • uninstall:删除项目的包

4. bower使用

1). 安装jQuery到项目nodejs-bower


~ D:\workspace\javascript\nodejs-bower>bower install jquery
bower jquery#*              not-cached git://github.com/components/jquery.git#*
bower jquery#*                 resolve git://github.com/components/jquery.git#*
bower jquery#*                download https://github.com/components/jquery/archive/2.0.3.tar.gz
bower jquery#*                 extract archive.tar.gz
bower jquery#*                resolved git://github.com/components/jquery.git#2.0.3
bower jquery#~2.0.3            install jquery#2.0.3

jquery#2.0.3 bower_components\jquery

通过执行命令,我们可以看到jQuery的最新版本被下载,并安装到项目的bower_components\jquery目录

查看bower_components/jquery目录,发现了3个文件。


~ D:\workspace\javascript\nodejs-bower>ls bower_components/jquery -a
.  ..  .bower.json  component.json  jquery.js

同样地,我们的项目还需要d3的类库


~ D:\workspace\javascript\nodejs-bower>bower install d3
bower d3#*                  not-cached git://github.com/mbostock/d3.git#*
bower d3#*                     resolve git://github.com/mbostock/d3.git#*
bower d3#*                    download https://github.com/mbostock/d3/archive/v3.2.8.tar.gz
bower d3#*                     extract archive.tar.gz
bower d3#*                    resolved git://github.com/mbostock/d3.git#3.2.8
bower d3#~3.2.8                install d3#3.2.8

d3#3.2.8 bower_components\d3

非常方便,下载并安装完成!

2). 查看项目中已导入的类库


~ D:\workspace\javascript\nodejs-bower>bower list
bower check-new     Checking for new versions of the project dependencies..
nodejs-bower#0.0.0 D:\workspace\javascript\nodejs-bower
├── d3#3.2.8
└── jquery#2.0.3

3). 安装bootstrap库,并查看依赖情况


~ D:\workspace\javascript\nodejs-bower>bower install bootstrap
bower bootstrap#*               cached git://github.com/twbs/bootstrap.git#3.0.0-rc1
bower bootstrap#*             validate 3.0.0-rc1 against git://github.com/twbs/bootstrap.git#*
bower jquery#>= 1.9.0           cached git://github.com/components/jquery.git#2.0.3
bower jquery#>= 1.9.0         validate 2.0.3 against git://github.com/components/jquery.git#>= 1.9.0
bower bootstrap#~3.0.0-rc1     install bootstrap#3.0.0-rc1

bootstrap#3.0.0-rc1 bower_components\bootstrap
└── jquery#2.0.3

~ D:\workspace\javascript\nodejs-bower>bower list
bower check-new     Checking for new versions of the project dependencies..
nodejs-bower#0.0.0 D:\workspace\javascript\nodejs-bower
├─┬ bootstrap#3.0.0-rc1 extraneous
│ └── jquery#2.0.3
├── d3#3.2.8
└── jquery#2.0.3

我们发现bootstrap,对jquery是有依赖的。

4). 删除jQuery库,破坏依赖关系


~ D:\workspace\javascript\nodejs-bower>bower uninstall jquery
bower conflict      bootstrap depends on jquery
Continue anyway? (y/n) y
bower uninstall     jquery

~ D:\workspace\javascript\nodejs-bower>bower list
bower check-new     Checking for new versions of the project dependencies..
nodejs-bower#0.0.0 D:\workspace\javascript\nodejs-bower
├─┬ bootstrap#3.0.0-rc1 extraneous
│ └── jquery missing
├── d3#3.2.8
└── jquery missing

5). 安装低版本的jQuery,制造不版本兼容


~ D:\workspace\javascript\nodejs-bower>bower install jquery#1.7.2
bower jquery#~2.0.3             cached git://github.com/components/jquery.git#2.0.3
bower jquery#~2.0.3           validate 2.0.3 against git://github.com/components/jquery.git#~2.0.3
bower jquery#>= 1.9.0           cached git://github.com/components/jquery.git#2.0.3
bower jquery#>= 1.9.0         validate 2.0.3 against git://github.com/components/jquery.git#>= 1.9.0
bower jquery#1.7.2              cached git://github.com/components/jquery.git#1.7.2
bower jquery#1.7.2            validate 1.7.2 against git://github.com/components/jquery.git#1.7.2

Unable to find a suitable version for jquery, please choose one:
    1) jquery#1.7.2 which resolved to 1.7.2
    2) jquery#~2.0.3 which resolved to 2.0.3 and has nodejs-bower as dependants
    3) jquery#>= 1.9.0 which resolved to 2.0.3 and has bootstrap#3.0.0-rc1 as dependants

Prefix the choice with ! to persist it to bower.json

Choice: 1
bower jquery#1.7.2             install jquery#1.7.2

jquery#1.7.2 bower_components\jquery

~ D:\workspace\javascript\nodejs-bower>bower list
bower check-new     Checking for new versions of the project dependencies..
nodejs-bower#0.0.0 D:\workspace\javascript\nodejs-bower
├─┬ bootstrap#3.0.0-rc1 extraneous
│ └── jquery#1.7.2 incompatible with >= 1.9.0 (2.0.3 available)
├── d3#3.2.8
└── jquery#1.7.2 incompatible with ~2.0.3 (2.0.3 available)

我们可以清楚的看到bower,很明确的告诉了我们,jquery和bootstrap是不兼容的,强大之处大家应该有所体会。

6).升级jQuery,让版本兼容


~ D:\workspace\javascript\nodejs-bower>bower update jquery
bower jquery#~2.0.3             cached git://github.com/components/jquery.git#2.0.3
bower jquery#~2.0.3           validate 2.0.3 against git://github.com/components/jquery.git#~2.0.3
bower jquery#>= 1.9.0           cached git://github.com/components/jquery.git#2.0.3
bower jquery#>= 1.9.0         validate 2.0.3 against git://github.com/components/jquery.git#>= 1.9.0
bower jquery#~2.0.3            install jquery#2.0.3

jquery#2.0.3 bower_components\jquery

~ D:\workspace\javascript\nodejs-bower>bower list
bower check-new     Checking for new versions of the project dependencies..
nodejs-bower#0.0.0 D:\workspace\javascript\nodejs-bower
├─┬ bootstrap#3.0.0-rc1 extraneous
│ └── jquery#2.0.3
├── d3#3.2.8
└── jquery#2.0.3

多么智能,一键搞定,这才是高效的开发。

7). 查看本地bower已经缓存的类库


~ D:\workspace\javascript\nodejs-bower>bower cache list
bootstrap=git://github.com/twbs/bootstrap.git#3.0.0-rc1
d3=git://github.com/mbostock/d3.git#3.2.8
jquery=git://github.com/components/jquery.git#1.7.2
jquery=git://github.com/components/jquery.git#2.0.3

8). 查看D3库信息


~ D:\workspace\javascript\nodejs-bower>bower info d3
d3

  Versions:
    - 3.2.8
    - 3.2.7
    - 3.2.6
    - 3.2.5
    - 3.2.4
    - 3.2.3
    ...

9). 查看dojo库的url


~ D:\workspace\javascript\nodejs-bower>bower lookup dojo
dojo git://github.com/dojo/dojo.git

10). 用浏览器打开dojo的发布主页


~ D:\workspace\javascript\nodejs-bower>bower home dojo
bower dojo#*                not-cached git://github.com/dojo/dojo.git#*
bower dojo#*                   resolve git://github.com/dojo/dojo.git#*
bower dojo#*                  download https://github.com/dojo/dojo/archive/1.9.1.tar.gz
bower dojo#*                   extract archive.tar.gz
bower dojo#*                  resolved git://github.com/dojo/dojo.git#1.9.1

浏览器自动打开:https://github.com/dojo/dojo

11). 查询包含dojo的类库


~ D:\workspace\javascript\nodejs-bower>bower search dojo
Search results:

    dojo git://github.com/dojo/dojo.git
    dojox git://github.com/dojo/dojox.git
    dojo-util git://github.com/dojo/util.git
    dojo-bootstrap git://github.com/samvdb/Dojo-Bootstrap

真是方便实用的技术。

5. 用bower提交自己类库

1). 生成bower.json配置文件


~ D:\workspace\javascript\nodejs-bower>bower init
bower existing      The existing bower.json file will be used and filled in
[?] name: nodejs-bower
[?] version: 0.0.0
[?] main file:
[?] set currently installed components as dependencies? No
[?] add commonly ignored files to ignore list? Yes

查看生成的文件bower.json


{
  "name": "nodejs-bower",
  "version": "0.0.0",
  "ignore": [
    "**/.*",
    "node_modules",
    "bower_components",
    "test",
    "tests"
  ],
  "dependencies": {
    "d3": "git://github.com/mbostock/d3.git#~3.2.8",
    "jquery": "git://github.com/components/jquery.git#~2.0.3"
  }
}

2). 在github创建一个资源库:nodejs-bower
3). 本地工程绑定github


~ D:\workspace\javascript\nodejs-bower>git init
Initialized empty Git repository in D:/workspace/javascript/nodejs-bower/.git/

~ D:\workspace\javascript\nodejs-bower>git add .
~ D:\workspace\javascript\nodejs-bower>git commit -m "first commit"
# On branch master
#
# Initial commit
#
# Untracked files:
#   (use "git add ..." to include in what will be committed)
#
#       app.js
#       bower.json
#       bower_components/
#       node_modules/
#       package.json
#       public/
#       routes/
#       views/
nothing added to commit but untracked files present (use "git add" to track)

~ D:\workspace\javascript\nodejs-bower>git remote add origin https://github.com/bsspirit/nodejs-bower

~ D:\workspace\javascript\nodejs-bower>git push -u origin master
Counting objects: 565, done.
Delta compression using up to 4 threads.
Compressing objects: 100% (516/516), done.
Writing objects: 100% (565/565), 803.08 KiB, done.
Total 565 (delta 26), reused 0 (delta 0)
To https://github.com/bsspirit/nodejs-bower
 * [new branch]      master -> master
Branch master set up to track remote branch master from origin.

4). 注册到bower官方类库


~ D:\workspace\javascript\nodejs-bower>bower register nodejs-bower git@github.com:bsspirit/nodejs-bower.git
bower                          convert Converted git@github.com:bsspirit/nodejs-bower.git to git://github.com/bsspirit/n
odejs-bower.git
bower nodejs-bower#*           resolve git://github.com/bsspirit/nodejs-bower.git#*
bower nodejs-bower#*          checkout master
bower nodejs-bower#*          resolved git://github.com/bsspirit/nodejs-bower.git#af3ceaac07
Registering a package will make it visible and installable via the registry (https://bower.herokuapp.com), continue? (y/
n)                    y
bower nodejs-bower            register git://github.com/bsspirit/nodejs-bower.git

Package nodejs-bower registered successfully!
All valid semver tags on git://github.com/bsspirit/nodejs-bower.git will be available as versions.
To publish a new version, you just need release a valid semver tag.

Run bower info nodejs-bower to list the package versions.

5). 查询我们自己的包


D:\workspace\javascript\nodejs-bower>bower search nodejs-bower
Search results:

    nodejs-bower git://github.com/bsspirit/nodejs-bower.git

6). 安装我们自己的包


D:\workspace\javascript\nodejs-bower>bower install nodejs-bower
bower nodejs-bower#*            cached git://github.com/bsspirit/nodejs-bower.git#af3ceaac07
bower nodejs-bower#*          validate af3ceaac07 against git://github.com/bsspirit/nodejs-bower.git#*
bower nodejs-bower#*           install nodejs-bower#af3ceaac07

nodejs-bower#af3ceaac07 bower_components\nodejs-bower
├── d3#3.2.8
└── jquery#2.0.3

其实模块化,版本依赖,开发类库,发布类库,安装类库,都是一条命令!还能再简单一点么!快把项目模块化,然后分享给大家吧!!未来是属于开发者的。

转载请注明出处:
http://blog.fens.me/nodejs-bower-intro/

打赏作者

grunt让Nodejs规范起来

从零开始nodejs系列文章,将介绍如何利Javascript做为服务端脚本,通过Nodejs框架web开发。Nodejs框架是基于V8的引擎,是目前速度最快的Javascript引擎。chrome浏览器就基于V8,同时打开20-30个网页都很流畅。Nodejs标准的web开发框架Express,可以帮助我们迅速建立web站点,比起PHP的开发效率更高,而且学习曲线更低。非常适合小型网站,个性化网站,我们自己的Geek网站!!

关于作者

  • 张丹(Conan), 程序员Java,R,PHP,Javascript
  • weibo:@Conan_Z
  • blog: http://blog.fens.me
  • email: bsspirit@gmail.com

转载请注明出处:
http://blog.fens.me/nodejs-grunt-intro/

grunt

前言
一个应用开发到一定阶段,普遍会遇到一个问题。当功能越来越多,代码量越来越大,bug修复越来越频繁,开发人员一波一波的交替,…..应该用会向着越来越不可控发展。我们不能再准确估计新功能的开发时间,也不知道一个bug修复后是否会引发另一个bug出现。所有的程序开发,都会面临着这样的问题。

C/C++程序通过makefile管理编译测试打包的过程,Java程序通过Maven,Ant实现项目构建管理功能,Python有pip,Ruby有gem。在Nodejs的领域,我们同样需要一个项目构建工具,这就是Grunt。Grunt可以执行像压缩, 编译, 单元测试, 代码检查以及打包发布的任务。

目录

  1. Grunt介绍
  2. Grunt安装
  3. Grunt使用
  4. Grunt常用插件:
    1).grunt-contrib-uglify:压缩js代码
    2).grunt-contrib-concat:合并js文件
    3).grunt-contrib-qunit:单元测试
    4).grunt-contrib-jshint:js代码检查
    5).grunt-contrib-watch:文件监控

1. Grunt介绍

Grunt是一个自动化的项目构建工具. 如果你需要重复的执行像压缩, 编译, 单元测试, 代码检查以及打包发布的任务. 那么你可以使用Grunt来处理这些任务, 你所需要做的只是配置好Grunt, 这样能很大程度的简化你的工作.

如果在团队中使用Grunt, 你只需要与其他人员约定好使用Grunt应该规避的问题, 就能够很方便的自动化的处理大部分的常见工作任务, 你所付出的努力几乎为0.

2. Grunt安装

Grunt和Grunt插件都是通过npm, Node.js包管理器安装和管理的.

我的系统环境

  • win7 64bit
  • Nodejs:v0.10.5
  • Npm:1.2.19
~ D:\workspace\javascript>node -v
v0.10.5

~ D:\workspace\javascript>npm -v
1.2.19

在系统中,我们已经安装好了Nodejs和npm。win7安装nodejs请参考文章:Nodejs开发框架Express3.0开发手记–从零开始

安装grunt-cli
grunt-cli并不grunt,grunt-cli的作用是管理本地各版本的grunt,让命令行可以直接执行grunt命令。

下面全局安装grunt-cli(-g)


~ D:\workspace\javascript>npm install -g grunt-cli

D:\toolkit\nodejs\grunt -> D:\toolkit\nodejs\node_modules\grunt-cli\bin\grunt
grunt-cli@0.1.9 D:\toolkit\nodejs\node_modules\grunt-cli
├── resolve@0.3.1
├── nopt@1.0.10 (abbrev@1.0.4)
└── findup-sync@0.1.2 (lodash@1.0.1, glob@3.1.21)

我们看到grunt-cli似乎做了一个软件链接,把grunt脚本复制到nodejs安装根目录里。

接下来全局安装grunt


~ D:\workspace\javascript>npm install -g grunt

~ D:\workspace\javascript>grunt
grunt-cli: The grunt command line interface. (v0.1.9)

Fatal error: Unable to find local grunt.

If you're seeing this message, either a Gruntfile wasn't found or grunt
hasn't been installed locally to your project. For more information about
installing and configuring grunt, please see the Getting Started guide:

http://gruntjs.com/getting-started

执行grunt命令,我们发现系统报错了,提示不能加载本地库。因为,grunt命令执行,是需要当前目录中包括package.json和Gruntfile.js两个文件。

package.json,是npm项目配置文件
Gruntfile.js,是专门用来配置grunt的配置文件

接下来,我们创建一个express3的项目。


~ D:\workspace\javascript>express -e nodejs-grunt
~ D:\workspace\javascript>cd nodejs-grunt && npm install	 
~ D:\workspace\javascript\nodejs-grunt>npm install grunt --save-dev

安装-save-dev,就可以,直接把grunt作为devDependencies写入的package.json中。


~ vi package.json

{
  "name": "nodejs-grunt",
  "version": "0.0.1",
  "private": true,
  "scripts": {
    "start": "node app.js"
  },
  "dependencies": {
    "express": "3.2.2",
    "ejs": "*"
  },
  "devDependencies": {
    "grunt": "~0.4.1",
  }
}

然后,我们再执行grunt,系统提示缺少Gruntfile文件


~ D:\workspace\javascript\nodejs-grunt>grunt
A valid Gruntfile could not be found. Please see the getting started guide for
more information on how to configure grunt: http://gruntjs.com/getting-started
Fatal error: Unable to find Gruntfile.

创建Gruntfile文件


~ vi Gruntfile.js

module.exports = function(grunt) {
  // Project configuration.
  grunt.initConfig({
    pkg: grunt.file.readJSON('package.json'),
    uglify: {
      options: {
        banner: '/*! <%= pkg.name %> <%= grunt.template.today("yyyy-mm-dd") %> */\n'
      },
      build: {
        src: 'src/<%= pkg.name %>.js',
        dest: 'build/<%= pkg.name %>.min.js'
      }
    }
  });
  // Load the plugin that provides the "uglify" task.
  grunt.loadNpmTasks('grunt-contrib-uglify');
  // Default task(s).
  grunt.registerTask('default', ['uglify']);
};

再次运行grunt,这时提示是grunt-contrib-uglify包找不到,是Gruntfile.js配置文件中的错误了。


~ D:\workspace\javascript\nodejs-grunt>grunt
>> Local Npm module "grunt-contrib-uglify" not found. Is it installed?
Warning: Task "uglify" not found. Use --force to continue.

我们编辑package.js, 在devDependencies中增加grunt-contrib-uglify的依赖库


~ vi package.js
{
  "name": "application-name",
  "version": "0.0.1",
  "private": true,
  "scripts": {
    "start": "node app.js"
  },
  "dependencies": {
    "express": "3.2.2",
    "ejs": "*"
  },
  "devDependencies": {
    "grunt": "~0.4.1"
    "grunt-contrib-uglify": "~0.1.1"
  }
}

~ D:\workspace\javascript\nodejs-grunt>npm install

我们创建两个目录src和build,和nodejs-grunt.js的文件


~ D:\workspace\javascript\nodejs-grunt>mkdir src
~ D:\workspace\javascript\nodejs-grunt>mkdir build

~ D:\workspace\javascript\nodejs-grunt>vi src/nodejs-grunt.js
var sayHello = function(name){
	return "Hello " + name;
}

我们再执行grunt


~ D:\workspace\javascript\nodejs-grunt>grunt
Running "uglify:build" (uglify) task
File "build/nodejs-grunt.min.js" created.
Uncompressed size: 59 bytes.
Compressed size: 40 bytes gzipped (43 bytes minified).

Done, without errors.

grunt运行正常,并且执行了uglify:build的任务。打开build/nodejs-grunt.min.js文件

~ D:\workspace\javascript\nodejs-grunt>vi build/nodejs-grunt.min.js

/*! nodejs-grunt 2013-08-17 */
var sayHello=function(l){return"Hello "+l};

我们可以看到一个新生成的压缩文件nodejs-grunt.min.js。

上面的例子,是一个js文件压缩的例子。

3. Grunt使用

我们可以通过help帮助,看一下grunt怎么用。


~ D:\workspace\javascript\nodejs-grunt>grunt --help
Grunt: The JavaScript Task Runner (v0.4.1)

Usage
 grunt [options] [task [task ...]]

Options
    --help, -h  Display this help text.
        --base  Specify an alternate base path. By default, all file paths are
                relative to the Gruntfile. (grunt.file.setBase) *
    --no-color  Disable colored output.
   --gruntfile  Specify an alternate Gruntfile. By default, grunt looks in the
                current or parent directories for the nearest Gruntfile.js or
                Gruntfile.coffee file.
   --debug, -d  Enable debugging mode for tasks that support it.
       --stack  Print a stack trace when exiting with a warning or fatal error.
   --force, -f  A way to force your way past warnings. Want a suggestion? Don't
                use this option, fix your code.
       --tasks  Additional directory paths to scan for task and "extra" files.
                (grunt.loadTasks) *
         --npm  Npm-installed grunt plugins to scan for task and "extra" files.
                (grunt.loadNpmTasks) *
    --no-write  Disable writing files (dry run).
 --verbose, -v  Verbose mode. A lot more information output.
 --version, -V  Print the grunt version. Combine with --verbose for more info.
  --completion  Output shell auto-completion rules. See the grunt-cli
                documentation for more information.

Options marked with * have methods exposed via the grunt API and should instead
be specified inside the Gruntfile wherever possible.

Available tasks
        uglify  Minify files with UglifyJS. *
       default  Alias for "uglify" task.

Tasks run in the order specified. Arguments may be passed to tasks that accept
them by using colons, like "lint:files". Tasks marked with * are "multi tasks"
and will iterate over all sub-targets if no argument is specified.

The list of available tasks may change based on tasks directories or grunt
plugins specified in the Gruntfile or via command-line options.

For more information, see http://gruntjs.com/

有两方面是我们需要注意的:

  1. Options: grunt支持的命令
  2. Available tasks: 当目录可执行的任务

4. Grunt常用插件

  • grunt-contrib-uglify:压缩js代码
  • grunt-contrib-concat:合并js文件
  • grunt-contrib-qunit:单元测试
  • grunt-contrib-jshint:js代码检查
  • grunt-contrib-watch:监控文件修改并重新执行注册的任务

1). grunt-contrib-uglify:是执行压缩JS代码的任务
具体操作请查看”2.Grunt安装”,

2). grunt-contrib-concat:是执行合并文件的任务。
插件安装及更新到配置


~ D:\workspace\javascript\nodejs-grunt>npm install grunt-contrib-concat --save-dev

修改Gruntfile.js文件


grunt.initConfig({
    pkg: grunt.file.readJSON('package.json'),
    concat:{
      options: {
        //定义一个字符串插入没个文件之间用于连接输出
        separator: ';'
      },
      dist: {
          src: ['src/*.js'],
          dest: 'build/<%= pkg.name %>.cat.js'
      }
    },
  });
grunt.loadNpmTasks('grunt-contrib-qunit');
grunt.registerTask('default', ['uglify','concat']);

在src目录,新增加文件src/sayBye.js


~ vi src/sayBye.js

var sayBye = function(name){
	return "Bye " + name;
}

执行concat任务


~ D:\workspace\javascript\nodejs-grunt>grunt concat
Running "concat:dist" (concat) task
File "build/nodejs-grunt.cat.js" created.

Done, without errors.

查看生成的文件build/nodejs-grunt.cat.js


~ vi build/nodejs-grunt.cat.js

var sayHello = function(name){
	return "Hello " + name;
};var sayBye = function(name){
	return "Bye " + name;
}

两个文件完全的合并。

3). grunt-contrib-qunit:是执行QUint单元测试的任务。

插件安装及更新到配置


~ D:\workspace\javascript\nodejs-grunt>npm install grunt-contrib-qunit --save-dev

修改Gruntfile.js文件


grunt.initConfig({
    pkg: grunt.file.readJSON('package.json'),
    qunit: {
      files: ['test/*.html']
    }
  });
grunt.loadNpmTasks('grunt-contrib-qunit');
grunt.registerTask('default', ['uglify','concat','qunit']);

创建一个test目录,并编写用于测试的qunit.html文件


~ mkdir test
~ vi test/qunit.html
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<link rel="stylesheet" href="http://github.com/jquery/qunit/raw/master/qunit/qunit.css" type="text/css" media="screen" />
<script type="text/javascript" src="http://github.com/jquery/qunit/raw/master/qunit/qunit.js"></script>
<script>
test("hello", function() {
ok(true, "world");
});
</script>
</head>
<body>
<h1 id="qunit-header">QUnit example</h1>
<h2 id="qunit-banner"></h2>
<h2 id="qunit-userAgent"></h2>
<ol id="qunit-tests"></ol>
</body>
</html>

执行qunit命令


~ D:\workspace\javascript\nodejs-grunt>grunt qunit
Running "qunit:files" (qunit) task
Testing test/qunit.html .OK
>> 1 assertions passed (67ms)

Done, without errors.

完成单元测试!!

4). grunt-contrib-jshint:是执行代码验证的任务
插件安装及更新到配置


~ D:\workspace\javascript\nodejs-grunt>npm install grunt-contrib-jshint --save-dev

修改Gruntfile.js文件


grunt.initConfig({
    pkg: grunt.file.readJSON('package.json'),
    jshint: {
        files: ['gruntfile.js', 'src/*.js', 'build/*.js'],
        options: {
            globals: {
                exports: true
            }
        }
    }
  });
grunt.loadNpmTasks('grunt-contrib-jshint');
grunt.registerTask('default', ['uglify','concat','qunit','jshint']);

执行jshint代码检查


~ D:\workspace\javascript\nodejs-grunt>grunt jshint
Running "jshint:files" (jshint) task
Linting src/nodejs-grunt.js ...ERROR
[L3:C2] W033: Missing semicolon.
}
Linting build/nodejs-grunt.cat.js ...ERROR
[L5:C2] W033: Missing semicolon.
}
Linting build/nodejs-grunt.min.js ...ERROR
[L2:C42] W033: Missing semicolon.
var sayHello=function(l){return"Hello "+l};

Warning: Task "jshint:files" failed. Use --force to continue.

Aborted due to warnings.

好多的错误啊,细看一下,都是”丢失分号”的错误。


~ vi src/sayBye.js
var sayBye = function(name){
	return "Bye " + name;
};

增加最后一行的分号,解决上面的错误。

5). grunt-contrib-watch,是监控指定文件被修改,重新启动已注册的任务
我感觉这个插入,就点类似于supervisor的功能。

插件安装及更新到配置


~ D:\workspace\javascript\nodejs-grunt>npm install grunt-contrib-watch --save-dev

修改Gruntfile.js文件


grunt.initConfig({
    pkg: grunt.file.readJSON('package.json'),
    watch: {
        files: ['<%= jshint.files %>'],
        tasks: ['jshint', 'qunit']
    }
  });
grunt.loadNpmTasks('grunt-contrib-watch');
grunt.registerTask('default', ['uglify','concat','qunit','jshint']);

执行watch任务


~ D:\workspace\javascript\nodejs-grunt>grunt watch
Running "watch" task
Waiting...OK

#手动修改src/sayBye.js文件,下面watch的任务被触发
>> File "src\sayBye.js" changed.

Running "jshint:files" (jshint) task
Linting src/sayBye.js ...ERROR
[L3:C2] W033: Missing semicolon.
}
Linting build/nodejs-grunt.cat.js ...ERROR
[L3:C3] W032: Unnecessary semicolon.
};;var sayBye = function(name){
Linting build/nodejs-grunt.min.js ...ERROR
[L2:C42] W033: Missing semicolon.
var sayHello=function(l){return"Hello "+l};

Warning: Task "jshint:files" failed. Use --force to continue.

Aborted due to warnings.
Completed in 0.770s at Sat Aug 17 2013 20:49:15 GMT+0800 (中国标准时间) - Waiting...

上面介绍的5个任务,可能是我们比较常用配置的任务,大家也可以按照需要指定自己的任务。

下面贴上所最终的package.json和Gruntfile.js文件代码

package.json


{
  "name": "nodejs-grunt",
  "version": "0.0.1",
  "private": true,
  "scripts": {
    "start": "node app.js"
  },
  "dependencies": {
    "express": "3.2.2",
    "ejs": "*"
  },
  "devDependencies": {
    "grunt": "~0.4.1",
    "grunt-contrib-uglify": "~0.1.1",
    "grunt-contrib-concat": "~0.3.0",
    "grunt-contrib-qunit": "~0.2.2",
    "grunt-contrib-jshint": "~0.6.3",
    "grunt-contrib-watch": "~0.5.2"
  }
}

Gruntfile.js


module.exports = function(grunt) {

  // Project configuration.
  grunt.initConfig({
    pkg: grunt.file.readJSON('package.json'),
    uglify: {
      options: {
        banner: '/*! <%= pkg.name %> <%= grunt.template.today("yyyy-mm-dd") %> */\n'
      },
      build: {
        src: 'src/<%= pkg.name %>.js',
        dest: 'build/<%= pkg.name %>.min.js'
      }
    },
    concat:{
      options: {
        //定义一个字符串插入没个文件之间用于连接输出
        separator: ';'
      },
      dist: {
          src: ['src/*.js'],
          dest: 'build/<%= pkg.name %>.cat.js'
      }
    },
    qunit: {
      files: ['test/*.html']
    },
    jshint: {
        files: ['gruntfile.js', 'src/*.js', 'build/*.js'],
        options: {
            globals: {
                exports: true
            }
        }
    },
    watch: {
        files: ['<%= jshint.files %>'],
        tasks: ['jshint', 'qunit']
    }
  });

  grunt.loadNpmTasks('grunt-contrib-uglify');
  grunt.loadNpmTasks('grunt-contrib-concat');
  grunt.loadNpmTasks('grunt-contrib-qunit');
  grunt.loadNpmTasks('grunt-contrib-jshint');
  grunt.loadNpmTasks('grunt-contrib-watch');

  // Default task(s).
  grunt.registerTask('default', ['uglify','concat','qunit','jshint']);

};

转载请注明出处:
http://blog.fens.me/nodejs-grunt-intro/

打赏作者