Node相關(guān)知識

使用commonjs規(guī)范:直接使用module.exports導(dǎo)出模塊,require導(dǎo)入
global下常用屬性有:process、buffer、setImmediate等

文件皆模塊,所以this屬性是{}(不是global)
__dirname,__filename => 當(dāng)前目錄,文件絕對路徑

process

  • version
  • platform
  • nextTick 優(yōu)先于promise.then
  • cwd() 當(dāng)前執(zhí)行命令的目錄(非文件所在目錄)的絕對路徑。使用chdir(dir)可以修改
  • env 用戶傳入的環(huán)境變量
    export/set NODE_ENV=dev && node xxx.js
  • argv 用戶傳入的執(zhí)行參數(shù)
    一個數(shù)組,[node所在目錄,項目執(zhí)行入口,...用戶參數(shù)]

commander 一個處理命令行參數(shù)的包

var cmd = require('commander');
cmd.command('myorder <param>')
   .option('-mo,-myorder', '我自己定義的命令')
   .action(() => {})
cmd.parse(process.argv) // {prot: 3000}

commonjs

文件皆模塊,直接使用module.exports導(dǎo)出模塊,require導(dǎo)入

實現(xiàn)邏輯:

  1. 一個名為require的方法,1個字符串入?yún)?/li>
  2. 取絕對路徑
  3. 取文件內(nèi)容
  4. 根據(jù)后綴執(zhí)行不同方法
  5. .js方法的:創(chuàng)建閉包 => vm.runInThisContext => 執(zhí)行
  6. 添加緩存
let path = require('path')
let fs = require('fs')
let vm = require('vm')    // 虛擬機(jī)模塊

function MyModule(dir) { 
  this.exports = {} 
  this.static_dir = dir
  this.ext = null
  this.file_content = null

  this.getStaticPath(dir)     // 取文件絕對路徑
  this.getContent()           // 取文件內(nèi)容
}

MyModule.prototype.getStaticPath = function (dir) {
  this.static_dir = path.resolve(__dirname, dir)    // 取文件絕對路徑
  this.ext = path.extname(dir)                      // 取文件擴(kuò)展名
}

MyModule.prototype.getContent = function () {
  if (this.ext) {
    this.file_content = this.readFile(this.static_dir)
  } else {
    Object.keys(MyModule.CodeHandler).forEach(key => {
      this.file_content = this.readFile(this.static_dir + key)
      if (this.file_content) {
        this.ext = key
        return false
      }
    })
  }
}

MyModule.prototype.readFile = function (dir) {
  try {
    return fs.readFileSync(dir, 'utf8')
  } catch {
    return null
  }
}

MyModule.prototype.compileCode = function () {
  if (!this.file_content) throw new Error('文件不存在')
  // 檢查緩存
  if (!MyModule._cache[this.static_dir]) {
    MyModule._cache[this.static_dir] = MyModule.CodeHandler[this.ext].call(this)
  }
  return MyModule._cache[this.static_dir]
}

MyModule._cache = {}    // 緩存
MyModule.CodeHandler = {
  '.json': function () {
    let json = JSON.parse(this.file_content)
    delete this.file_content
    return json
  },
  '.js': function () {
    // 閉包
    let true_module = `(function (module, exports, req, __dirname, __filename) { 
      ${this.file_content} 
    })`;
    delete this.file_content

    vm.runInThisContext(true_module)    // 無污染的eval
      // 不用call,引入文件中的this會指向global
      // 指向this.exports, 當(dāng)不使用module.exports導(dǎo)出時,把文件內(nèi)this.xxx的內(nèi)容返回
      //(就像 node require 一樣)
      .call(this.exports, this, this.exports, req, __dirname, __filename)
    return this.exports
  }
}

function req (dir) {
  return new MyModule(dir).compileCode()
}



let temp1 = req('./temp/runcode-node.js')
console.log(temp1)
console.log('-------------------------')
let temp2 = req('./temp/runcode-node.js')
console.log(temp2)
console.log('-------------------------')
let temp = require('./temp/runcode-node.js')
console.log(temp)
// ./temp/runcode-node.js
this.b = 88
let a = { say: 'yes, you got me', t: new Date() }
console.log( process.argv, __filename, this, exports, '~~~')  //Object.keys( process),

module.exports = a
exports = this.b

inquirer

const inquirer = require('inquirer')
const questions = [
  {
    type : "input",
    name : "sender.email",
    message : "Sender's email address - "
  },
  {
    type : "input",
    name : "sender.name",
    message : "Sender's name - "
  },
  {
    type: 'list',
    message: '請選擇一種水果:',
    name: 'fruit',
    choices: [
        "Apple",
        "Pear",
        "Banana"
    ]
  }
]
inquirer.prompt(questions).then(function (answers) {
    console.log(answers)
})
image.png

Node Event Loop

每個類型都有自己的隊列,主棧執(zhí)行完后,依次執(zhí)行

  1. timer 定時器
  2. pending callback 錯誤?
  3. idle prepare 內(nèi)部調(diào)用?
  4. poil 輪尋
  5. check 檢查 -> go 1, start over
  6. close callbacks

.
.
.
.
left knowledge points for me
調(diào)度打點、webpack調(diào)試
.

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容