react,react native,webpack,ES6,node.js----------今天上午学了一下node.js

http://www.yiibai.com/nodejs/node_install.html---node.js具体入门资料在此

 


 

Node JS事件循环

Node JS是单线程应用程序,但它通过事件和回调概念,支持并发。 由于Node JS每一个API是异步的,作为一个单独的线程,它使用异步函数调用,以保持并发性。Node JS使用观察者模式。Node线程保持一个事件循环,每当任何任务得到完成,它触发这标志着该事件侦听器函数执行相应的事件。

事件驱动编程

Node.js大量使用事件,这也是为何Node.js是相当快相对于其他类似的技术。当Node启动其服务器,它可以简单地启动它的变量,声明的函数,然后简单地等待发生的事件。

在事件驱动的应用中,通常主循环监听事件,然后触发回调函数时被检测到这些事件之一。

Event Loop

尽管事件似乎类似于回调。不同之处在于如下事实,当异步函数返回其结果的回调函数被调用的地方作为对观察者模式的事件处理。 监听事件的功能作为观察员。每当一个事件被触发,它的监听函数就开始执行。Node.js具有多个内置通过事件模块和用于将事件绑定和事件侦听,如下EventEmitter类可用事件:

// Import events module
var events = require('events');
// Create an eventEmitter object
var eventEmitter = new events.EventEmitter();

以下为事件处理程序绑定使用事件的语法:

// Bind event and even handler as follows
eventEmitter.on('eventName', eventHandler);

我们可以通过编程触发一个事件,如下所示:

// Fire an event 
eventEmitter.emit('eventName');

例子

创建一个名为具有以下代码main.js一个js文件:

// Import events module
var events = require('events');
// Create an eventEmitter object
var eventEmitter = new events.EventEmitter();

// Create an event handler as follows
var connectHandler = function connected() {
   console.log('connection succesful.');
  
   // Fire the data_received event 
   eventEmitter.emit('data_received');
}

// Bind the connection event with the handler
eventEmitter.on('connection', connectHandler);
 
// Bind the data_received event with the anonymous function
eventEmitter.on('data_received', function(){
   console.log('data received succesfully.');
});

// Fire the connection event 
eventEmitter.emit('connection');

console.log("Program Ended.");

现在让我们试着运行上面的程序作为检查的输出:

$ mnode main.js

这将产生以下结果:

connection succesful.
data received succesfully.
Program Ended.

Node应用程序是如何工作的?

在Node应用程序,任何异步函数接受回调作为最后的参数和回调函数接受错误的第一个参数。我们再看一下前面的例子了。创建一个名为input.txt的有以下内容的文本文件

Yiibai Point is giving self learning content
to teach the world in simple and easy way!!!!!

创建一个名为具有以下代码的main.js一个js文件:

var fs = require("fs");

fs.readFile('input.txt', function (err, data) {
   if (err){
      console.log(err.stack);
      return;
   }
   console.log(data.toString());
});
console.log("Program Ended");

这里fs.readFile()是一个异步函数,其目的是要读取文件。如果在文件的读出发生了错误,则er对象将包含相应的错误,否则数据将包含该文件的内容。readFile传递err和数据,回调函数后,文件读取操作完成,并最终打印的内容。

Program Ended
Yiibai Point is giving self learning content
to teach the world in simple and easy way!!!!!


模块全局安装和本地安装的区别

 

如果一个包是要当做命令一样的来使用,就推荐进行全局安装,如下
$ npm -g install the_module_name

而如果一个包是使用在项目里面的话,则使用本地安装,这样避免了不同项目对不同版本的包之间的相互依赖的问题,如下
$ npm install the_module_name

具体区别:
1.安装位置:
npm install moduleName ,则是将模块下载到当前命令行所在目录。
npm install moduleName -g ,模块将被下载安装到全局目录中,即Node的安装目录下的node_modules下

2.调用方式:
在代码中,本地安装可以直接通过require()的方式引入;var moduleName = require('moduleName');
全局的安装是供命令行(command line)使用的,比如grunt,全局安装的方式是没有办法用require调用包的;
[注]:卸载模块包时也分全局和本地(-g),而且
$ npm ls -g 验证全局包
$ npm ls  验证本地包
 

 

posted @ 2016-07-18 09:10  天才老王1993  阅读(254)  评论(0编辑  收藏  举报