简体   繁体   English

Node.js 中有什么要求

[英]What require does in Node.js

I was wondering how could an exported function that uses npm modules in it, run in another file which doesn't require these npm packages?我想知道在其中使用 npm 模块的导出 function 怎么能在另一个不需要这些 npm 包的文件中运行?

First file (which will be exported):第一个文件(将被导出):

    const jwt = require("jsonwebtoken")
    var generateToken = function (){var token = jwt.sign({name:"medo"},"sas");return token}

    module.exports = generateToken

Second file (which will require the function):第二个文件(需要该功能):

    const token = require("./pack.js")
    console.log(token());

How does the function work successfully in the second file, when the jsonwebtoken module is not required in it?jsonwebtoken模块时,function 如何在第二个文件中成功工作?

It's a dependency tree.这是一个依赖树。 Your code loaded ./pack.js .您的代码已加载./pack.js In the process of loading that file, it then loaded the module jsonwebtoken .在加载该文件的过程中,它随后加载了模块jsonwebtoken ./pack.js , then exports it's own function generateToken() and your code can then call generateToken() . ./pack.js ,然后导出它自己的 function generateToken()然后您的代码可以调用generateToken()

When generateToken() executes, it uses the jwt object that it previously imported in order to do its job.generateToken()执行时,它使用之前导入的jwt object 来完成它的工作。

The only thing that was successfully called from your file was the generateToken() function that was exported from ./pack.js .从您的文件中成功调用的唯一内容是从 ./pack.js 导出的generateToken() ./pack.js That gererateToken() function then executes in the scope of its own module where it has access to the things that it required in such as jwt . gererateToken() function 然后在它自己的模块的 scope 中执行,它可以访问它所需的东西,例如jwt


Its analagous to what happens in operating system calls all the time.它类似于操作系统调用中一直发生的事情。 You call an operating system function to play an audio file.您调用操作系统 function 来播放音频文件。 That operating system function then loads an appropriate sound driver (if not already loaded) and an appropriate codec for decompressing the type of sound file.该操作系统 function 然后加载适当的声音驱动程序(如果尚未加载)和适当的编解码器以解压缩声音文件的类型。 Your code didn't have to load those things.您的代码不必加载这些东西。 You just called the OS function to play the sound file.您刚刚调用了操作系统 function 来播放声音文件。 It's the implementation of that function inside the OS that loads all the right pieces to actually carry out that function.它是在操作系统中执行 function 加载所有正确的部分以实际执行 function。 Same in your nodejs example.在您的 nodejs 示例中也是如此。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM