简体   繁体   English

从动态外部文件运行Nodejs函数

[英]Running Nodejs Function from Dynamic External File

I want to know if there is a way to run a Node function from an external file which is subject to change. 我想知道是否有一种方法可以从可能会更改的外部文件中运行Node函数。

Main.js Main.js

function read_external(){
    var external = require('./external.js');
    var result = external.result();
    console.log(result);
}

setInterval(function(){
    read_external();
},3000);

External.js ( Initial ) External.js(初始)

exports.result = function(){
    return "James"; // Case 1
}

I now run the code by typing node main.js 我现在通过键入节点main.js运行代码

After the code starts running, I changed the External.js to 代码开始运行后,我将External.js更改为

exports.result = function(){
    return "Jack"; // Case 2
}

However inspite of the change, it keeps printing James and not Jack. 无论有什么变化,它都会继续打印James而不是Jack。 Is there a way to write the code such a way that the new function gets executed when the code is changed ? 有没有一种方法可以编写代码,以便在更改代码时执行新功能?

I need this as I am building a service where people can provide their own scripts as JS files and it gets executed when they call a certain function in the service depending on who is calling it. 我在构建服务时需要这样做,人们可以在其中提供自己的脚本作为JS文件,并且当他们根据谁在调用服务中的某个函数时,该脚本就会执行。

Node.js will cache calls to the same file so it doesn't have to fetch it again. Node.js将缓存对相同文件的调用,因此不必再次提取该文件。 To get the file as if it were new you'll need to clear the cache in require.cache . 要获得新文件,您需要清除require.cache的缓存。 The key for the file should be the resolved name which you can look up with require.resolve() 该文件的密钥应该是解析的名称,您可以使用require.resolve()查找该名称。

You can remove the module from cache before each call. 您可以在每次调用之前从缓存中删除模块。

var module = require.resolve('./external.js');

function read_external(){
    var external = require(module);
    var result = external.result();
    console.log(result);
}

setInterval(function(){
    delete require.cache[module]; //clear cache
    read_external();
},3000);

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

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