回调
vi readfile.txt
写点测试数据在里面
vi test.js
var fs = require("fs");
fs.readFile('readfile.txt', function(err,data){
if(err) return console.error(err);
condole.log(data.toString());
});
console.log("finished the program!");
然后执行
node test.js
不需要等待文件读取完,这样就可以在读取文件时同时执行接下来的代码,非阻塞
node.js是单线程,它的事件机制是用设计模式中观察者模式实现
javaScript语言只有字符串数据类型,但在处理tcp或文件流时,要用到二进制数据,所以node.js中定义了一个buffer类,感觉类似数组.
var buf1 = new Buffer('abc');
var buf2 = new Buffer('def');
var buf3 = Buffer.concat([buffer1,buffer2]);
console.log("buffer3内容:" + buffer3.toString());
Buffer还有很多方法,比如tojson,compare
创建模块
vi main.js
var hello = require('./hello');
hello.workd();
这里引用了hello,所以我们来创建个hello.js
vi hello.js
exports.world = function(){
console.log('Hello World');
}
或者
vi hello.js
function Hello(){
var name;
this.setName = function(thyName){
name = thyName;
}
this.sayHello = function(){
console.log('hello ' + name);
}
};
module.exports = Hello;
然后可以在main.js中这样用
var Hello = require('./hello');
hello = new Hello();
hello.setName('Lawson');
hello.sayHello();
写的比较乱