首先下载node.js,然后解压到D盘,配置好后,打开cmd用cd命令切换到nodejs目录。
实例一:Hello world
在node目录下建立hello文件夹,并在其下新建hello.js文件,在里面输入:
var sys = require("sys"); sys.puts("Hello world");
然后在命令台中输入命令node hello.js,就能看到命令台输出结果Hello world。
实例二:从浏览器中输出Hello World
在node\hello目录下建立helloworld.js文件,内容如下:
var sys = require("sys"), http = require("http"); http.createServer(function(request, response) { response.writeHead(200, {"Content-Type": "text/html"}); response.write("Hello World!"); response.end(); }).listen(8090); sys.puts("Server running at http://localhost:8090/");
然后在命令台中输入node helloworld。
在浏览器输入http://localhost:8090/
实例三:node.js提供一个Buffer类用于转换不同编码的字符串,目前支持三种类型:'ascii'、'utf8'与'binary'
在node\hello目录下建立helloworld2.js文件,内容如下:
var Buffer = require('buffer').Buffer, buf = new Buffer(256), len = buf.write('\u00bd + \u00bc = \u00be', 0); console.log(len + " bytes: " + buf.toString('utf8', 0, len));
然后在命令台中输入node helloworld2。