nodejs模块使用及简单的示例
参考菜鸟教程网:http://www.runoob.com/
一.fs模块的使用:
1.文件操作:
读文件:
//读文件 var fs=require('fs'); //阻塞(同步) var data=fs.readFileSync('test.txt'); console.log(data.toString()); //非阻塞(异步) fs.readFile('test.txt',function(err,data){ if(err){ return console.error(err); }else{ console.log(data.toString()); } });
写文件:
//写文件 var fs=require('fs');
//覆盖文件: //阻塞(同步) var content='zlllllllaaaaaallllsssdff'; fs.writeFile('test.txt',content); //非阻塞(异步) var content='zzzzzzzzzzz11111zzzzzzzzzz'; fs.writeFileSync('test.txt',content); //追加 //阻塞(同步) var content='zlllllllaaaaaallllsssdff'; fs.appendFile('test.txt',content); //非阻塞(异步) var content='zzzzzzzzzzz11111zzzzzzzzzz'+' 张三'; fs.appendFileSync('test.txt',content);
2.文件流操作:
读文件流:
//读文件流 var fs=require('fs'); var data=''; var readStream=fs.createReadStream('test.txt'); readStream.setEncoding('utf-8'); readStream.on('data',function(chuck){ data+=chuck; }); readStream.on('end',function(){ console.log(data); }); readStream.on('err',function(err){ console.log(err.stack); });
写文件流:
//写文件流 var vale='zzzz'; var writeStream=fs.createWriteStream('test.txt'); writeStream.write(vale); writeStream.end(); writeStream.on('finish',function(){ console.log('success'); }); readStream.on('err',function(err){ console.log(err.stack); });
二.events模块使用:
//事件操作 var event=require('events'); //创建eventEmitter对象 var eventEmitter=new event.EventEmitter(); //绑定事件,并回调 eventEmitter.on('test-name',function(){ console.log('事件绑定并回调成功!'); }); //触发事件 eventEmitter.emit('test-name');