---
title: "服务端JavaScript"
author: "faiinlove"
date: "2009-10-12T23:35:59Z"
tags: []
slug: "javascript"
draft: false
lastmod: "2009-10-12T23:38:20Z"
id: 486542
url: "https://obatu.iteye.com/blog/486542"
---

自从Ajax流行以来，JS以其灵活的垄断的特性占据Web客户端开发语言霸主地位。虽然JS非常强大，但是它仅仅只能用在客户端浏览器上，是应用于客户端编程的语言，比如说Ajax之类的效果，利用异步的处理流程，无法在服务端使用如此灵活的语言实在是一大憾事啊！

不过现在，你完全可以在服务端使用JS了，赋予你这种能力的神兵利器就是[node.js](http://nodejs.org/)，按照官方的介绍：它是Evented I/O for [V8 javascript](http://code.google.com/p/v8/)。主要的优点就是：

- **可以非常简单的构建可扩展网络应用；**
- **同传统的基于线程的解决方式相比，node.js则不会直接执行IO处理；**
- **执行过程本身是无锁的，节省内存，从而大大提升处理并发的效率。**

在Linux下安装还是那样：

./configure 配置  
make  编译  
make install 安装

一个Hello, World的服务端演示程序（helloword.js）：

```
include("/utils.js");    //导入包
include("/http.js");

createServer(function (req, res) {  //创建服务
    setTimeout(function () {            //执行一个定时程序
        res.sendHeader(200, {"Content-Type": "text/plain"});
        res.sendBody("Hello World");
        res.finish();
    }, 2000);
}).listen(8000);

puts("Server running at http://127.0.0.1:8000/"); //输出一句话

```

   
保存然后执行：/usr/local/bin/node helloword.js

 

执行后，服务程序会监听8000端口，一旦有请求过来，就会执行方法。在这个实例中，定时器会等待2秒钟，然后输出Hello World，最重要的是，在这个2秒的等待过程中，服务端还会处理其他的请求，相当于java的多线程了。

 

node.js功能确实强大，如下面这篇文章：

[Streaming file uploads with node.js](http://www.debuggable.com/posts/streaming-file-uploads-with-node-js:4ac094b2-b6c8-4a7f-bd07-28accbdd56cb) 写道

Streaming file uploads with node.js  
Posted 2 weeks ago by Felix Geisendörfer

Not excited by hello world in node.js? No problem.

Let's say you are a startup focusing on upload technology and you want the maximum level of control for your file uploads. In our case that means having the ability to directly interact with the multipart data stream as it comes in (so we can abort the upload if something isn't right, - beats the hell out of letting the user wait an hour to tell him after the upload has finished).

Here is a complete example on how to accomplish this in node.js (you'll need the bleeding edge git version):

var http = require('/http.js');  
var multipart = require('/multipart.js');

var server = http.createServer(function(req, res) {  
switch (req.uri.path) {  
case '/':  
display\_form(req, res);  
break;  
case '/upload':  
upload\_file(req, res);  
break;  
default:  
show\_404(req, res);  
break;  
}  
});  
server.listen(8000);

function display\_form(req, res) {  
res.sendHeader(200, {'Content-Type': 'text/html'});  
res.sendBody(  
'&lt;form action="/upload" method="post" enctype="multipart/form-data"&gt;'+  
'&lt;input type="file" name="upload-file"&gt;'+  
'&lt;input type="submit" value="Upload"&gt;'+  
'&lt;/form&gt;'  
);  
res.finish();  
}

function upload\_file(req, res) {  
req.setBodyEncoding('binary');

var stream = new multipart.Stream(req);  
stream.addListener('part', function(part) {  
part.addListener('body', function(chunk) {  
var progress = (stream.bytesReceived / stream.bytesTotal * 100).toFixed(2);  
var mb = (stream.bytesTotal / 1024 / 1024).toFixed(1);

print("Uploading "+mb+"mb ("+progress+"%)\\015");

// chunk could be appended to a file if the uploaded file needs to be saved  
});  
});  
stream.addListener('complete', function() {  
res.sendHeader(200, {'Content-Type': 'text/plain'});  
res.sendBody('Thanks for playing!');  
res.finish();  
puts("\\n=&gt; Done");  
});  
}

function show\_404(req, res) {  
res.sendHeader(404, {'Content-Type': 'text/plain'});  
res.sendBody('You r doing it rong!');  
res.finish();  
}  
The code is rather straight forward. First of all we include the multipart.js parser which is a library that has just been added to node.js.

Next we create a server listening on port 8000 that dispatches incoming requests to one of our 3 functions: display\_form, upload\_file or show\_404. Again, very straight forward.

display\_form serves a very short (and invalid) piece of HTML that will render a file upload form with a submit button. You can get to it by running the example (via: node uploader.js) and pointing your browser to http://localhost:8000/.

upload\_file kicks in as soon as you select a file and hit the submit button. It tells the request object to expect binary data and then passes the work on to the multipart Stream parser. The result is a new stream object that emits two kinds of events: 'part' and 'complete'. 'part' is called whenever a new element is found within the multipart stream, you can find all the information about it by looking at the first argument's headers property. In order to get the actual contents of this part we attach a 'body' listener to it, which gets called for each chunk of bytes getting uploaded. In our example we just use this event to render a progress indicator in our command line, but we could also append this chunk to a file which would eventually become the entire file as uploaded from the browser. Finally the 'complete' event sends a response to the browser indicating the file has been uploaded.

show\_404 is handling all unknown urls by returning an error response.

As you can see, the entire process is pretty simple, yet gives you a ton of control. You can also easily use this technique to show an AJAX progress bar for the upload to your users. The multipart parser also works with non-HTTP requests, just pass it the {boundary: '...'} option into the constructor and use steam.write() to pass it some data to parse. Check out the source of the parser if you're curious how it works internally.

-- Felix Geisendörfer aka the\_undefined

   
如果你在执行代码的时候遇到如下错误：

Error: print() has moved. Use include('/utils.js') to bring it back.

不妨在脚本头部加上include('/utils.js')，这是因为node.js还在高速发展中，代码更新的比较快。

设想一下，如果有一天，我们在客户端使用jquery之类的js客户端工具，在服务端使用node.js之类的服务端工具，那么编程只靠Javascript就能一条龙通吃了，再也不用像个学生一样一会儿学语文，一会儿还要学英语，这真是一件有趣的事情。