自从Ajax流行以来,JS以其灵活的垄断的特性占据Web客户端开发语言霸主地位。虽然JS非常强大,但是它仅仅只能用在客户端浏览器上,是应用于客户端编程的语言,比如说Ajax之类的效果,利用异步的处理流程,无法在服务端使用如此灵活的语言实在是一大憾事啊!
不过现在,你完全可以在服务端使用JS了,赋予你这种能力的神兵利器就是node.js,按照官方的介绍:它是Evented I/O for V8 javascript。主要的优点就是:
- 可以非常简单的构建可扩展网络应用;
- 同传统的基于线程的解决方式相比,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
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(
'<form action="/upload" method="post" enctype="multipart/form-data">'+
'<input type="file" name="upload-file">'+
'<input type="submit" value="Upload">'+
'</form>'
);
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=> 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就能一条龙通吃了,再也不用像个学生一样一会儿学语文,一会儿还要学英语,这真是一件有趣的事情。
分享到:
相关推荐
RingoJS是一个基于Java平台的服务端JavaScript框架,它允许开发者使用JavaScript进行全栈开发,将JavaScript的灵活性扩展到了服务器端。这个框架的核心是Rhino JavaScript引擎,一个由Mozilla开发的高性能JavaScript...
RingoJS是一个基于Java平台的轻量级服务端JavaScript框架,它允许开发者使用JavaScript语言来构建高性能、可扩展的Web应用程序。这个实例源码提供了一个深入理解RingoJS工作原理和开发流程的机会。 首先,RingoJS的...
关于文件名称列表中的"服务端JavaScript框架 RingoJS",这可能是指包含RingoJS框架的源代码、文档、示例应用或其他相关资源的压缩包。解压后,开发者可以深入研究其内部结构,学习如何配置和使用RingoJS,或者直接...
RingoJS是一个基于Java平台的服务端JavaScript框架,它允许开发者使用JavaScript语言来编写服务器端的应用程序,打破了JavaScript仅限于浏览器客户端使用的传统观念。RingoJS利用了Java的V8 JavaScript引擎,提供了...
JAVA源码服务端JavaScript框架RingoJS
RingoJS是一个基于Java平台的服务端JavaScript框架,它允许开发者使用JavaScript语言来编写服务器端的应用程序,从而打破了JavaScript仅用于客户端脚本的传统观念。RingoJS利用了Java的JVM(Java虚拟机)来运行...
java资源服务端JavaScript框架 RingoJS提取方式是百度网盘分享地址
RingoJS是一个基于Java平台的开源服务端JavaScript框架,它允许开发者使用JavaScript语言来构建高性能、可扩展的网络应用程序。这个框架的设计理念是提供一种轻量级、灵活且高效的解决方案,使得JavaScript不再仅仅...
除了Node.js,还有一些其他框架和库也支持服务端JavaScript,比如Deno,它是由Node.js的创建者Ryan Dahl推出的全新JavaScript/TypeScript运行时。Deno提供了一种更现代、更安全的环境,内置了 TypeScript 支持和权限...
RingoJS是一个开源的、基于Java的服务器端JavaScript框架,它允许开发者使用JavaScript语言来编写全功能的Web应用。这个框架的设计目标是提供一个高效、轻量级且易于使用的环境,使得JavaScript开发者能够利用Java...
RingoJS是一个强大的开源框架,它允许开发人员在Java平台上使用JavaScript进行服务器端开发。这个框架结合了Java的稳定性和JavaScript的灵活性,为开发者提供了一种高效、高性能的方式来构建Web应用。下面将详细介绍...
本篇文章将详细介绍MongoDB服务端JavaScript脚本的使用方法。 首先,我们来看一些在MongoDB中常用的JavaScript语句。例如,db.getSiblingDB()用于切换到指定的数据库,db.getCollectionNames()用于获取当前数据库中...
免责声明:资料部分来源于合法的互联网渠道收集和整理,部分自己学习积累成果,供大家学习参考与交流。收取的费用仅用于收集和整理资料耗费时间的酬劳。 本人尊重原创作者或出版方,资料版权归原作者或出版方所有,...
node.js-v12.16.1安装包,和yarn-1.22.4安装包的...Node.js是一个事件驱动I/O服务端JavaScript环境,基于Google的V8引擎,V8引擎执行Javascript的速度非常快,性能非常好。 yarn 为快速、可靠、安全的依赖管理工具。
资源名称:Node.js参考手册 中文CHM版内容...Node.js是一个事件驱动I/O服务端Javascript环境,基于Google的V8引擎,V8引擎执行Javascript的速度 资源太大,传百度网盘了,链接在附件中,有需要的同学自取。
- **服务端JavaScript**:介绍了Node.js的基本概念及其在服务端的应用。 综上所述,《JavaScript权威指南》第六版是一本详尽且全面的参考书籍,不仅覆盖了JavaScript语言的核心概念和技术,还深入探讨了其在Web...
全栈开发人员:在开发过程中需要调试客户端或服务端JavaScript代码的全栈工程师。 新手程序员:刚开始学习JavaScript编程,需要理解代码执行流程的新手。 高级开发人员:希望提升调试效率和代码质量的资深开发者。 ...
- **简介**:Aptana提供的一个服务端JavaScript运行环境,支持FTP、SMTP、HTTP等协议,并集成了多个流行的JavaScript库(如jQuery、Dojo和ExtJS)。 - **应用场景**:适用于需要在服务器端执行JavaScript代码的...