node.js 学习笔记(1)/9.26

node.js核心模块:

1.nodejs全局变量是global,不是window

2.process 进程对象

3.console.log() 控制台输出

内置模块

1.util //功能不详,貌似是继承Sub,Base这两个类的

   (.eg)1 util.inherits(Sub, Base); 

2.events //功能不详

3.fs //file stream?

 (.eg)

1 var fs = require("fs"); 
2 fs.readFile("file.txt", "utf-8", readFileCallBack);

 4.HTTP服务器与客户端

http.Server事件

http.SeverRequest\http.SeverRespnse

1 var http = require("http");
2 
3 function start(req, res){
4     res.writeHead(200, {"Contnet-Type": "text/html"});
5     res.write("<h1>NodeJs</h1>");
6     res.end("<p>The End</p>")
7 }
8 
9 http.createServer(start).listen(3000);

 

模块与包

1.创建模块 

2.Express框架(mvc)

 ------------------------------------------------------------华丽丽的分割线啊啊啊啊啊~~~~~--------------------------------------------------------------------

learning source: http://www.open-open.com/lib/view/1392611872538(此部分较为简略)

模块:require, exports, module (key words)

require:用于在当前模块中加载和使用别的模块,传入一个模块名,返回一个模块导出对象。模块名可使用相对路径(以 ./ 开头),或者是绝对路径(以 / 或 c:之类的盘符开头)。另外,模块名中的 .js扩展名可以省略。以下是一个例子。

var foo = require("./foo"); //相对路径
var foo1 = require("./foo.js"); //js可以省略
var foo2 = require("/home/foo.js") //绝对路径

//comparetively we also can require json,but with behind-address .json

var json = require("./j.json");

  

  exports: exports 对象是当前模块的导出对象,用于导出模块公有方法和属性。别的模块通过 require函数使用当前模块时得到的就是当前模块的 exports对象。以下例子中导出了一个公有方法。

exports.hello = function(){
    console.log("hello world!");
}

 

  module:通过 module对象可以访问到当前模块的一些相关信息,但最多的用途是替换当前模块的导出对象。例如模块导出对象默认是一个普通对象,如果想改成一个函数的话,可以使用以下方式。

module.exports = function () {
    console.log('Hello World!');
};
//以上代码中,模块默认导出对象被替换为一个函数。

  1.模块初始化 

  模块中的js代码只在模块被使用时执行一次,并在执行过程中初始化js导出对象 exports ,之后重复利用使用对象

  主模块:通过命令行参数传递给NodeJS以启动程序的模块被称为主模块。主模块负责调度组成整个程序的其它模块完成工作。例如通过以下命令启动程序时,main.js就是主模块。

var counter1 = require('./util/counter');
var  counter2 = require('./util/counter');

//...some other operation

  counter.js存在一个私有变量,一个公有获取方法。

var i = 0;
function count(){
    i++;
}
exports.count = count;

  在main中调用

console.log(counter1.count());
console.log(counter2.count());
//输出 1, 2

part1总结:

1.安装nodejs的本质是,把nodejs执行程序复制到一个目录,而且这个目录在系统PATH环境变量下,以便终端使用node执行

2.使用CMD模块系统,主模块作为程序入口,每个模块在执行过程中只初始化一次。

posted @ 2014-09-26 15:31  totoSalad  阅读(120)  评论(0编辑  收藏  举报