Node.js 不是一种独立的语言,与PHP、Python、Perl、Ruby的“既是语言也是平台”不同
也不是一个 JavaScript 框架, 不同于CakePHP、Django、Rails
更不是浏览器端的库,不能与浏览器端, jQuery、ExtJS的库相提并论
Node.js 是一个让 JavaScript 运行在服务端的开发平台,它让 JavaScript 成为脚本语言世界的一等公民,在服务端堪与 PHP、Python、Perl、Ruby 平起平坐。
<span style="font-family: Arial, Helvetica, sans-serif;">第一章、</span>
<span style="font-family: Arial, Helvetica, sans-serif;">var http=require('http'); 首先获取node.js 原生http模块对象</span>
http.createServer(function(req,res){
<span style="white-space:pre"> </span>res.writeHead(200,{'Content-Type':'text/html'});/*接收内容格式*/
<span style="white-space:pre"> </span>res.write('<p>kerry is beauty!</p>');
<span style="white-space:pre"> </span>res.end('oh__ohohohoh');/*结束内容接受,必须写否者浏览器会一直在加载状态*/
}).listen(3000); /*监听本地ip,3000端口*/
console.log('test1 0k!');
本篇只是因为小白最近在学习node.js,所以单独写了一篇来记录学习笔记,有不对的希望大家多多提出,后续一定更正,谢谢!!<img alt="大笑" src="http://static.blog.youkuaiyun.com/xheditor/xheditor_emot/default/laugh.gif" />
第二章、req对象有addListener()方法,并携带两个时间‘data’和‘end’ 两个事件(ps:必须是字符串格式 )
data是有数据传到服务器时候是触发 的时间 end是客户端传递完成所有数据后触发的时间
querystring字符串处理
dns.resolve
第2.1.5章
exports 和module.exports的作用是把文件模块的方法暴露给require返回的对象中进行调用。但是两者还是有一些本质的区别,exports的属性和方法都可以被module.exports替代,所有的exports对象最终是通过module.exports传递执行,确切的是exports是给module.exports添加的属性和方法
socket.io 双向传值例子
index_client.html
<html>
<head>
<title></title>
<script src="./node_modules/socket.io-client/socket.io.js"></script>
<script type="text/javascript">
function doit() {
var socket = io.connect('http://localhost:3000');
socket.on('news', function (data) {//接收到服务器发送过来的名为'new'的数据
console.log(data.hello);//data为应服务器发送过来的数据。
socket.emit('my new event', { my:'new data' });//向服务器发送数据,实现双向数据传输
});
socket.on('other', function (data) {//接收另一个名为'other'数据,
console.log(data.hello);
socket.emit('my new event', { my:'other data' });
});
}
</script>
</head>
<body>
<button id='btn' οnclick="doit()">click me</button>
</body>
index_server.js
var app = require('http').createServer(handler)
var io = require('socket.io')(app);
var fs = require('fs');
app.listen(3000);
function handler (req, res) {
fs.readFile(__dirname + '/index_client.html',
function (err, data) {
if (err) {
res.writeHead(500);
return res.end('Error loading index.html');
}
res.writeHead(200);
res.end(data);
});
}
io.on('connection', function (socket) {
socket.emit('other', { hello: 'world1' });
socket.on('my new event', function (data) {
console.log(data);
});
});
这样一个socket.io的例子就好了
supervisor 可以帮助你实现这个功能,它会监视你对代码的改动,并自动重启 Node.js。使用方法很简单,首先使用 npm 安装 supervisor:$ npm install -g supervisor如果你使用的是 Linux 或 Mac,直接键入上面的命令很可能会有权限错误。原因是 npm需要把 supervisor 安装到系统目录,需要管理员授权,可以使用 sudo npm install -gsupervisor 命令来安装。接下来,使用 supervisor 命令启动 app.js:$ supervisor app.js
function callback(err,data){ 将文件内容作为函数的返回值赋给data变量
if(err){
console.log(err);
}else{
console.log(data);
}
}
fs模块是对文件的处理 fs.readFileSync('file.txt', 'utf-8' ,callback); 有三个参数,一个是文件名,第二个是编码格式,第三个是回调函数 这个是同步读取文件
fs.readFile('file.txt', 'utf-8' ,callback); 异步读取文件
require 不会重复加载模块