饥人谷技术博客

Nodejs 入门

2017-12-06  本文已影响25人  辉夜乀

nodejs 是什么

nodejs is a JavaScript runtime built on Chrome's V8
nodejs 并不是一门语言,而是一个运行环境
特点:

非阻塞I/O

事件驱动

为什么前端偏爱nodejs

CPU密集 VS I/O密集

web 常见场景

高并发应对之道

进程

nodejs 环境

一个栗子

image

nodejs 自动帮我们做了,外面包了一个函数,实现模块化。

CommonJS

require 规则

require 特性

nodejs 内置模块

api文档

第三方模块 node_modules

module.exports 与 exports 的区别

const exports = modules.exports
    //exports 是 module.exports 的快捷方式
    
exports.test = 100;
    //可以给 exports 添加属性。
    
exports = {
    test: 150
}   //这是错误的用法,因为改变了 exports 的指向,模块输出找不到。

module.exports = {
    test: 200
}   //这是可以的,因为输出的模块是 module.exports

global 全局对象

把变量赋给 global 对象作为属性,则所有的文件都能拿到该变量。

timer

来看一下三个的执行顺序


image image

可以看到,执行顺序是 nextTicksetImmediate要早,而setTimeout由设定的时间来决定,如果时间为0,则是在两个事件队列之间。

上一篇 下一篇

猜你喜欢

热点阅读