nodejs模块加载的猜想
来源:互联网 发布:mac转音频格式 编辑:程序博客网 时间:2024/05/20 18:20
nodejs的模块化就相当于其他语言的类文件的导入和使用。
require方法与页面js的导入外部js文件不同。你在页面从外部导入一个js文件,比如:
server.js:
var http=require("http");function start(){function reqts(r,rsp){console.log("Request received");rsp.writeHead(200,{"Content-Type":"text/plaint"});rsp.write("Hello World");rsp.end();}http.createServer(reqts).listen(8888);console.log("Server has started.");}
你在页面直接可以这样使用:
start();
但是在nodejs,你用require引入一个js文件,你不能使用的。
比如在index.js引入这个server.js:
var server=require("./server.js");
这个和页面js有什么不同?有:
第一,这个require返回了一个对象,这个对象是什么内容暂时未知,至少我们知道有一个对象;
第二,如果你在引入之后直接调用:start();是不行的,说明这个require不知简单的把代码包含进来那么简单。
官方推荐是这样使用的:
server.js:
var http=require("http");function start(){function reqts(r,rsp){console.log("Request received");rsp.writeHead(200,{"Content-Type":"text/plaint"});rsp.write("Hello World");rsp.end();}http.createServer(reqts).listen(8888);console.log("Server has started.");}<span style="color:#ff0000;">exports.start=start;</span>
在index.js这样写:
var server=require("./server");<span style="color:#ff0000;">server.start();</span>
经过测试,发现如果没有exports.start=start;这个赋值,后面这个server.start();调用不会成功,说明他们存在因果关系。
推测,这个require返回的就是exports对象,把代码稍微修改一下:
server.js:
var http=require("http");function start(){function reqts(r,rsp){console.log("Request received");rsp.writeHead(200,{"Content-Type":"text/plaint"});rsp.write("Hello World");rsp.end();}http.createServer(reqts).listen(8888);console.log("Server has started.");}<span style="color:#ff0000;">exports.sta=start;</span>
index.js:
var server=require("./server");<span style="color:#ff0000;">server.sta();</span>
运行成功,证实了require返回exports的猜测。
更进一步,这个require是如何引用这个代码的?因为不能直接访问server.js里面的变量以及函数,猜测可能是闭包了,改造一下,直接把start函数暴露出来试试:
server.js:
var http=require("http");<span style="color:#ff0000;">start=function()</span>{function reqts(r,rsp){console.log("Request received");rsp.writeHead(200,{"Content-Type":"text/plaint"});rsp.write("Hello World");rsp.end();}http.createServer(reqts).listen(8888);console.log("Server has started.");}index.js:
var server=require("./server");<span style="color:#ff0000;">start();</span>
运行成功,说明真的是被闭包了。
0 0
- nodejs模块加载的猜想
- nodejs 的模块加载
- nodejs的模块加载小结
- nodeJs模块的理解以及加载方式
- nodejs模块加载机制
- nodejs 加载模块
- nodejs 模块加载机制
- NodeJs模块加载机制
- es6模块加载 nodejs(common.js)模块加载 amd模块加载的区别整理
- nodejs 动态加载模块 _compile
- nodeJS基础--模块加载机制
- NodeJS的模块原理
- nodejs的模块机制
- nodejs的模块引用
- nodejs 模块的流程
- NodeJS的模块机制
- nodejs 的q模块
- nodejs的HTTP模块
- 通过服务器返回来JSON歌词数据进行解析
- JAVA 课堂笔记
- setsockopt
- Eclipse常用快捷键
- Nim游戏,Grundy函数介绍
- nodejs模块加载的猜想
- HDU2018
- mysql 单表查询 空值查询
- for循环入门
- vofuria的开发(4)更换目标图片(target)
- R时间序列分析
- 原生javascript实现图片轮播效果——续
- L2-003. 月饼
- 把数组排成最小的数