一个 Node.js 文件就是一个模块,这个文件可能是JavaScript 代码、JSON 或者编译过的C/C++ 扩展。

模块是Node.js 应用程序的基本组成部分,文件和模块是一一对应的。

Node.js 工具模块

在 Node.js 模块库中几种常用模块的使用:

序号 模块名 & 描述
1 OS 模块
提供基本的系统操作函数。
2 Path 模块
提供了处理和转换文件路径的工具。
3 Net 模块
用于底层的网络通信。提供了服务端和客户端的的操作。
4 DNS 模块
用于解析域名。
5 Domain 模块
简化异步代码的异常处理,可以捕捉处理try catch无法捕捉的。

创建模块

调用函数

  • 形式一:

定义一个对外的world功能:定义一个对外的函数。

// hello.js

exports.world = function() {  // world() 成为 exports 对象的成员函数
console.log('Hello World');
}

在 main.js 中通过 require('./hello') 加载这个模块,然后就可以直接访 问 hello.js 中 exports 对象的成员函数了。

var hello = require('./hello');  // var hello 代表了一个模块,也就是./hello这个文件代表的东西
hello.world();
  • 形式二:【更流行】

定义一个对外的counter功能:定义一个函数,之后再使其对外。

Use this api (counter) here.

调用类

//main.js
var Hello = require('./hello');
hello = new Hello();
hello.setName('BYVoid');
hello.sayHello();

模块定义方法:

//hello.js
function Hello() {
var name;
this.setName = function(thyName) {
name = thyName;
};
this.sayHello = function() {
console.log('Hello ' + name);
};
};
module.exports= Hello;

(1) 其实也是开放多个对外函数的一个tricky方法:

(2) 以上较为麻烦。我们用类包裹多个函数,然后再导出该类,这样岂不是会轻便些。

模块加载

var http = require("http");

当文件模块缓存中不存在

而且不是原生模块的时候,

Node.js 会解析 require 方法传入的参数,并从文件系统中加载实际的文件

  • require方法接受以下几种参数的传递:
1 http、fs、path等 原生模块
2 ./mod 或 ../mod 相对路径的文件模块
3 /pathtomodule/mod 绝对路径的文件模块
4 mod 非原生模块的文件模块

在路径 Y 下执行 require(X) 语句执行顺序,参见链接

函数作为参数

两种写法,推荐后者。

function sayHI() { ... }

var Bye = function ([args]) { ... }

这么用的意义在于什么?

"做什么""谁去做"分离开来,也就是将‘不变的事物’和‘可变的事物’分离开来。

比如:有这么一个,它是功能参数的粘合剂!

function execute(someFunction, value) {
someFunction(value);
} function say(word) {
  console.log(word);
}
execute(say, "Hello");

或者,匿名函数方式,看起来简洁一些。

function execute(someFunction, value) {
someFunction(value);
} execute(function(word){ console.log(word) }, "Hello");

Node.js 全局对象

全局对象(Global Object),它及其所有属性都可以在程序的任何地方访问,即全局变量。

  1. 在浏览器 JavaScript 中,通常 window 是全局对象,
  2. 在 Node.js 中的全局对象是 global,所有全局变量(除了 global 本身以外)都是 global 对象的属性。

在 Node.js 我们可以直接访问到 global 的属性,而不需要在应用中包含它。

  • global 的属性

global 最根本的作用是作为全局变量的宿主。按照 ECMAScript 的定义,满足以下条 件的变量是全局变量:

    1. 在最外层定义的变量;
    2. 全局对象的属性;
    3. 隐式定义的变量(未定义直接赋值的变量)。

当你定义一个全局变量时,这个变量同时也会成为全局对象的属性,反之亦然。

需要注意的是,在 Node.js 中你不可能在最外层定义变量,因为所有用户代码都是属于当前模块的, 而模块本身不是最外层上下文。

  • 若干常用属性
// 输出全局变量 __filename 的值
console.log( __filename );
--------------------------------------
// 输出全局变量 __dirname 的值
console.log( __dirname );
--------------------------------------
function printHello(){
console.log( "Hello, World!");
}
// 两秒后执行以上函数
setTimeout(printHello, 2000);
--------------------------------------
function printHello(){
console.log( "Hello, World!");
}
// 两秒后执行以上函数
var t = setTimeout(printHello, 2000); // 清除定时器
clearTimeout(t);
--------------------------------------
function printHello(){
console.log( "Hello, World!");
}
// 两秒后执行以上函数
setInterval(printHello, 2000); 
  • console 方法

console 用于提供控制台标准输出,它是由 Internet Explorer 的 JScript 引擎提供的调试工具,后来逐渐成为浏览器的实施标准。

Node.js 沿用了这个标准,提供与习惯行为一致的 console 对象,用于向标准输出流(stdout)或 标准错误流(stderr)输出字符。

console.log('byvoid%diovyb');
console.log('byvoid%diovyb', 1991);   // 有%d就看有没有匹配的变量,有则“替换”,无则“失效”

console.error():与console.log() 用法相同,只是向标准错误流输出。

console.exception() 是 console.error() 的别名;它们功能相同。

console.trace();

Trace:
at Object.<anonymous> (/home/byvoid/consoletrace.js:1:71)
at Module._compile (module.js:441:26)
at Object..js (module.js:459:10)
at Module.load (module.js:348:31)
at Function._load (module.js:308:12)
at Array.0 (module.js:479:10)
at EventEmitter._tickCallback (node.js:192:40)
console.info("程序开始执行:");

console.time("获取数据");    // 表示计时开始

console.timeEnd('获取数据');  // 表示计时结束

console.info("程序执行完毕。")
  • process方法

参见:[Node.js] 06 - Multi-thread and process module

Node.js 常用工具

util 是一个Node.js 核心模块,提供常用函数的集合,用于弥补核心JavaScript 的功能 过于精简的不足。

  • util.inherits

util.inherits(constructor, superConstructor)是一个实现 对象间原型继承 的函数。

JavaScript 的面向对象特性是基于原型的,与常见的基于类的不同。JavaScript 没有 提供对象继承的语言级别特性,而是通过原型复制来实现的。

在这里我们只介绍util.inherits 的用法,示例如下:

var util = require('util'); 
function Base() {
this.name = 'base';
this.base = 1991;
this.sayHello = function() {
console.log('Hello ' + this.name);
};
}
Base.prototype.showName = function() {
console.log(this.name);
};
function Sub() {
this.name = 'sub';
}
util.inherits(Sub, Base);   // 继承的实现:继承自Base的Sub
var objBase = new Base();
objBase.showName();
objBase.sayHello();
console.log(objBase);
var objSub = new Sub();
objSub.showName();
//objSub.sayHello();
console.log(objSub);

Jeff: 关于js的类的设计问题,需要专题讲解。

  • util.inspect

将任意对象转换 为字符串的方法,通常用于调试和错误输出。

var util = require('util'); 
function Person() {
this.name = 'byvoid';
this.toString = function() {
return this.name;
};
}
var obj = new Person();
console.log(util.inspect(obj));
console.log(util.inspect(obj, true));

Result:

Person { name: 'byvoid', toString: [Function] }
Person {
name: 'byvoid',
toString:
{ [Function]
[length]: 0,
[name]: '',
[arguments]: null,
[caller]: null,
[prototype]: { [constructor]: [Circular] } } }
  • util.isArray(object)

如果给定的参数 "object" 是一个数组返回true,否则返回false。

var util = require('util');

util.isArray([])
// true
util.isArray(new Array)
// true
util.isArray({})
// false
  • util.isRegExp(object)

如果给定的参数 "object" 是一个正则表达式返回true,否则返回false。

var util = require('util');

util.isRegExp(/some regexp/)
// true
util.isRegExp(new RegExp('another regexp'))
// true
util.isRegExp({})
// false
  • util.isDate(object)

如果给定的参数 "object" 是一个日期返回true,否则返回false。

var util = require('util');

util.isDate(new Date())
// true
util.isDate(Date())
// false (without 'new' returns a String)
util.isDate({})
// false
  • util.isError(object)

如果给定的参数 "object" 是一个错误对象返回true,否则返回false。

var util = require('util');

util.isError(new Error())
// true
util.isError(new TypeError())
// true
util.isError({ name: 'Error', message: 'an error occurred' })
// false

[Node.js] 05 - Modules and Function的更多相关文章

  1. node --experimental-modules & node.js ES Modules

    node --experimental-modules & node.js ES Modules how to run esm modules in node.js cli $ node -v ...

  2. Node.js & ES Modules & Jest

    Node.js & ES Modules & Jest CJS & ESM CommonJS https://en.wikipedia.org/wiki/CommonJS ht ...

  3. Node.js & ES modules & .mjs

    Node.js & ES modules & .mjs Node.js v13.9.0 https://nodejs.org/api/esm.html https://nodejs.o ...

  4. [Node.js] 4. Modules

    4.2 Missing Exports Notice the two different files: high_five.js on the left side andapp.js on the r ...

  5. [Node.js] Exporting Modules in Node

    In this lesson, you will learn the difference between the exports statement and module.exports. Two ...

  6. [Node.js] CommonJS Modules

    CoomonJS modules provide a clean syntax for importing dependencies. This lesson will take a look at ...

  7. Node.js学习 - Modules

    创建模块 当前目录:hello.js, main.js // hello.js exports.world = function() { // exports 对象把 world 作为模块的访问接口 ...

  8. Node.js module export async function

    一.Demo 1.首先定义 module 文件:bbb.js const fs = require("fs"); function readFileSync() { let res ...

  9. Node.js require 模块加载原理 All In One

    Node.js require 模块加载原理 All In One require 加载模块,搜索路径 "use strict"; /** * * @author xgqfrms ...

随机推荐

  1. Redis集群官方推荐方案 Redis-Cluster

    Redis-Cluster redis使用中遇到的瓶颈 我们日常在对于redis的使用中,经常会遇到一些问题 1.高可用问题,如何保证redis的持续高可用性. 2.容量问题,单实例redis内存无法 ...

  2. Python爬虫实例:糗百

    看了下python爬虫用法,正则匹配过滤对应字段,这里进行最强外功:copy大法实践 一开始是直接从参考链接复制粘贴的,发现由于糗百改版导致失败,这里对新版html分析后进行了简单改进,把整理过程记录 ...

  3. json与xml数据输出类

    class Response { /** * 按json方式输出通信数据 * @param integer $code 状态码 * @param string $message 提示信息 * @par ...

  4. R12.1.3 & R12.2.X 注册客户化应用

    R12.2 官方出了运行补丁脚本就可以自动创建客户化应用,所以也把此补丁应用在 R12.1.3上验证一下其可行性,做出以下实验. 1.创建客户化应用账号CUX --login user system ...

  5. SSE图像算法优化系列四:图像转置的SSE优化(支持8位、24位、32位),提速4-6倍

    一.前言 转置操作在很多算法上都有着广泛的应用,在数学上矩阵转置更有着特殊的意义.而在图像处理上,如果说图像数据本身的转置,除了显示外,本身并无特殊含义,但是在某些情况下,确能有效的提高算法效率,比如 ...

  6. APICloud和海马玩模拟器结合调试手机页面

    https://blog.csdn.net/pleasecallme_522/article/details/54577904

  7. vue中使用some删除list中的数据

    在vue中可以使用some方法查找需要删除的所以 this.list.some((item, i) => { if (item.id == id) { this.list.splice(i, 1 ...

  8. 1分钟试用PowerShell 5.0新功能PowerShellGet安装Script Browser和Script Analyzer

    微软PowerShell 产品组上周发布了PowerShell 5.0 PowerShellGet功能.有了它,IT 人员可以方便地搜索,安装,更新PowerShell Module.在这篇博客中,我 ...

  9. 带参数的sigmoid

    $y=\frac{1}{1+e^{-(\alpha\times x+\beta)}}$ alpha越大,曲线越陡峭,beta控制平移 import numpy as np import pylab a ...

  10. [转载]js正则表达式/replace替换变量方法

    原文地址:http://www.blogjava.net/pingpang/archive/2012/08/12/385342.html JavaScript正则实战(会根据最近写的不断更新) 1.j ...