nodejs 第一次使用

时间:2022-01-13 18:30:44

在win7下安装与使用

1 nodejs官网下载,安装  https://nodejs.org/

2 下载最新的 npm,在E:\nodejs\中解压  http://nodejs.org/dist/npm/

高级系统设置->高级->环境变量->系统变量 中

path中添加 E:\nodejs\

新建 NODE_PATH E:\nodejs\node_modules\

3 命令行下输入 node -v 显示版本,表示安装成功。

4 把nodejs官网的代码拷贝到E:\nodejs\中,保存成一个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/');

5 命令行下输入 node service.js 会显示 Server running at http://127.0.0.1:1337/ 表示启动服务器成功。

6 在浏览器中输入 http://127.0.0.1:1337/,会显示 hello,word。

在node.js搭建的服务器端环境下运行html文件(来自http://www.cnblogs.com/shawn-xie/archive/2013/06/06/3121173.html)

var PORT = 3000;
var http = require('http');
var url=require('url');
var fs=require('fs');
var mine=require('./mine').types;
var path=require('path'); var server = http.createServer(function (request, response) {
var pathname = url.parse(request.url).pathname; var realPath = path.join("h5/study/", pathname);
console.log(realPath);
var ext = path.extname(realPath);
ext = ext ? ext.slice(1) : 'unknown';
fs.exists(realPath, function (exists) {
if (!exists) {
response.writeHead(404, {
'Content-Type': 'text/plain'
}); response.write("This request URL " + pathname + " was not found on this server.");
response.end();
} else {
fs.readFile(realPath, "binary", function (err, file) {
if (err) {
response.writeHead(500, {
'Content-Type': 'text/plain'
});
response.end(err);
} else {
var contentType = mine[ext] || "text/plain";
response.writeHead(200, {
'Content-Type': contentType
});
response.write(file, "binary");
response.end();
}
});
}
});
});
server.listen(PORT);
console.log("Server runing at port: " + PORT + ".");