Node.js:调用纯Javascript函数 [英] Node.js: calling pure Javascript functions

查看:129
本文介绍了Node.js:调用纯Javascript函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用Nodejs编写一些示例程序。我正面临着从Nodejs中调用Javascript文件的问题。假设我有3个.js文件:A.js,B.js,C.js. A.js是用Node编写的。 B.js和C.js是用纯Javascript编写的。现在我需要从A.js调用B.js中的函数b()。所以我eval()B.js并导出方法b()。这工作正常。但问题是当我在B.js中的函数b()调用C.js中的函数c()时。

I am using Nodejs for writing some sample programs. I am facing an issue with calling Javascript files from within Nodejs. Say I have 3 .js files: A.js, B.js, C.js. A.js is written in Node. B.js and C.js are written in pure Javascript. Now i need to call a function b() present in B.js from A.js. So I eval() B.js and export the method b(). This works properly. But the issue is when my function b() in B.js calls a function c() in C.js.

B.js:

function b()
{
    console.log('In function b');
    c();
}

C.js:

function c()
{
    console.log('In function c');
}

只是添加问题。我在B.js的全局空间中有一个B.js变量:var abc。
在C.js中我可以引用它:var a = abc;如何确保我的C.js可以访问我的变量abc?

Just to add on to the question. I have a var in B.js: var abc, in the global space of B.js. In C.js I can reference to it as just: var a = abc; How to make sure my C.js can have access to my variable abc?

我如何确保依赖性得到解决?任何帮助,将不胜感激。谢谢!!!

How do i make sure the dependancy is resolved? Any help would be appreciated. Thanks!!!

推荐答案

你应该使用模块。这很简单,只需阅读文档。

You should use modules in Node.js. It very simple, just read the docs.

B.js

var c = require('./C');

function b() {
    console.log('In function b');
    c();
}

C.js

module.exports = function() {
    console.log('In function c');
}

这篇关于Node.js:调用纯Javascript函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆