node——4-node 中的 js

版权声明:未经同意,不得随意转载转载 https://blog.csdn.net/lucky541788/article/details/83822003
  • 支持 EcmaScript
    • 区别:没有 DOM、BOM
  • 核心模块
  • 第三方模块
  • 用户自定义模块

核心模块

Node 为 JavaScript 提供了很多服务器级别的 API,这些 API 绝大多数都被包装到了一个具名的核心模块中了
例如:文件操作的 fs 核心模块,http 服务构建的 http 模块,path 路径操作模块,os 操作系统信息模块。。。

模块加载:var fs = require('fs');
// 用来获取机器信息的
var os = require('os');

// 用来获取当前机器的 cpu 信息
console.log(os.cpus());// 一堆 cpu 信息

// 用来获取当前机器的 memory 内存
console.log(os.totalmem());// 8512643072

// 用来操作路径的
var path = require('path');

// extension name 扩展名
console.log(path.extname('E:/desk/my-pro/QD-practice/node/1/code/myname.txt'));// .txt

用户自定义模块

注意:require 相对路径必须加 ./
推荐:可以省略后缀名
在这里插入图片描述

在 Node 中,没有全局作用域,只有模块作用域

  • 外部访问不到内部
  • 内部也访问不到外部

在这里插入图片描述

模块之间传值

require 方法有两个作用

  1. 加载文件模块并执行里面的代码
  2. 拿到被加载文件模块导出的接口对象
  • 在每个文件模块中都提供了一个对象:exports ,exports 默认是一个空对象,把所有需要被外部访问的成员挂载到这个 exports 对象中

2.js 文件内容传给 1.js
1.js

var res = require('./2');

console.log(res.foo);// hello

console.log(res.add(20, 10));// 30

2.js

var foo = 'hello';

// console.log(exports);// {}

exports.foo = foo;

exports.add = function (x, y) {
    return x + y;
};

猜你喜欢

转载自blog.csdn.net/lucky541788/article/details/83822003