zzhbbdbbd
V2EX  ›  Node.js

Node 如何判断载入的模块是内建模块还是 npm 安装的其他第三方模块

  •  
  •   zzhbbdbbd · Jul 23, 2018 · 5042 views
    This topic created in 2872 days ago, the information mentioned may be changed or developed.

    比如引入了

    const fs = require('fs')
    const express = require('express')
    

    如何判断 fs 和 express 哪个是内建模块,哪个是第三方模块

    11 replies    2018-07-23 19:54:12 +08:00
    Tonni
        2
    Tonni  
       Jul 23, 2018
    ```
    require.resolve('jquery').includes('node_modules')
    ```
    这样?
    yangg
        3
    yangg  
       Jul 23, 2018
    const builtinMods = new Set(Object.keys(process.binding('natives')).filter(x => !/^_|^(internal|v8|node-inspect)/.test(x)))
    buildinMods.has('fs')
    123s
        4
    123s  
       Jul 23, 2018
    你是想随便了解一下还是?
    zzhbbdbbd
        5
    zzhbbdbbd  
    OP
       Jul 23, 2018
    @yangg 这个原理是什么
    zzhbbdbbd
        6
    zzhbbdbbd  
    OP
       Jul 23, 2018
    @Tonni 有道理,这样确实可以
    zzhbbdbbd
        7
    zzhbbdbbd  
    OP
       Jul 23, 2018
    @123s 是这样的,我最近在写一份 tslint 的自定义 rule,该 rule 的主要功能就是区分 import 的模块的类型,把模块分类,然后代码格式化
    zzhbbdbbd
        8
    zzhbbdbbd  
    OP
       Jul 23, 2018
    @yangg 谢谢,刚刚没看到
    yangg
        9
    yangg  
       Jul 23, 2018
    @zzhbbdbbd 1 楼那个包的源码,
    `process.binding` returns internal module, like require. It's not public, so you shouldn't rely on it in your code, but you can use it to play with node's low level objects, if you want to understand how things work.

    For example, here timer_wrap binding is registered. It exports Timer constructor. In lib/timers.js it's imported

    https://stackoverflow.com/questions/24042861/nodejs-what-does-process-binding-mean

    你可以直接看 process.binding('fs')就知道大概他是干嘛的了
    kfll
        10
    kfll  
       Jul 23, 2018   ❤️ 1
    1. require.resolve(x) === x
    2. require.resolve.paths(x) === null 需要 8.9
    3. process.binding(x) 私有接口,还包括一些不能 require 的内部模块
    zzhbbdbbd
        11
    zzhbbdbbd  
    OP
       Jul 23, 2018
    @kfll 谢谢你的方案,我已经在用了:)
    About   ·   Help   ·   Advertise   ·   Blog   ·   API   ·   FAQ   ·   Solana   ·   3386 Online   Highest 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 64ms · UTC 11:12 · PVG 19:12 · LAX 04:12 · JFK 07:12
    ♥ Do have faith in what you're doing.