# NodeJS

# nodejs 是什么?

nodejs 是基于 Chrome V8 引擎的 javascript 运行时

运行时,即运行环境;而 Chrome V8 的话,相当于 js 语言在另一种运行环境的解释器。

# commonjs 与 ES6 Module 的区别?

  • commonjs 是动态引入,执行时引入
  • ES6 Module 是静态引入,编译时引入,ssr 的组件库时会考虑到这个。

示例

// ES6 Module 是静态引入,编译时引入,所以必须放在最外层
import { sum, test } from "./utils";

// const flag = true
// if(flag) {
//   import { sum, test } from './utils' // 放在 if 语句里 编译时 就会报错
// }

// CommonJs 引入
const http = require("http");

const flag = true;
if (flag) {
  const { sum, test } = require("./utils"); // commonJs 中是不会报错的
}

# path.resolve 与 path.join

  • path.resolve 得到是拼接后的绝对路径

  • path.join 得到是拼接后的绝对路径

const path = require("path");

// /Users/xxx/code-study/blog-han/docs/node/src/test
console.log(path.resolve("..", "src", "test"));

// ../src/test
console.log(path.join("..", "src", "test"));

# dirname 与 filename

  • __dirname 执行文件的文件目录路径

  • __filename 执行文件的整个路径(包含文件自身信息)

// 执行 node 1.js

// /Users/hanzhizhen/code-study/blog-han/docs/node/mianshi
console.log(__dirname);

// /Users/hanzhizhen/code-study/blog-han/docs/node/mianshi/1.js
console.log(__filename);

# 浏览器的 event loop

浏览器 js 的异步分为:

  1. 宏任务:setTimeout、setInterval、ajax 等

  2. 微任务:Promise async/await

  3. 微任务比宏任务执行时机更早

  4. Call Stack 空闲时,触发 Event Loop 机制,执行宏任务;但是触发 Event Loop 之前,如果有微任务存在,会优先将 微任务 执行完