[英]importing and running functions from javascript files with node
I have a simple javascript question.我有一个简单的 javascript 问题。 I have two files, a.js and b.js defined in the same directory.我在同一目录中定义了两个文件 a.js 和 b.js。
Within a.js I define a function:在 a.js 中,我定义了一个函数:
function foo() {
console.log('Hello World!');
}
in b.js I have:在 b.js 我有:
var a = require('./../scenarios/a.js');
a.foo();
However, when I run node b.js, I get:但是,当我运行 node b.js 时,我得到:
b.js:4
a.foo();
^
TypeError: a.foo is not a function
at Object.<anonymous> (/Users/dlumma/dev/bloomguild-applitools-sunbasket/scenarios/b.js:4:3)
at Module._compile (module.js:573:30)
at Object.Module._extensions..js (module.js:584:10)
at Module.load (module.js:507:32)
at tryModuleLoad (module.js:470:12)
at Function.Module._load (module.js:462:3)
at Function.Module.runMain (module.js:609:10)
at startup (bootstrap_node.js:158:16)
at bootstrap_node.js:598:3
Any clue what I am doing wrong?任何线索我做错了什么?
You need to export the function before accessing it.您需要在访问该函数之前导出该函数。
a.js
: a.js
:
function foo() {
console.log('Hello World!');
}
exports.foo = foo;
You should then be able to access it in b.js
.然后你应该可以在b.js
访问它。
Within a.js
:在a.js
:
module.exports = {
foo: function() {
console.log('Hello World!');
}
}
Then in b.js
:然后在b.js
:
var a = require('./scenarios/a.js');
a.foo();
I was able to figure this out!我能够弄清楚这一点! module.exports needs to be defined. module.exports 需要定义。 Ah the joys of learning JavaScript from the beginning!啊,从头开始学习 JavaScript 的乐趣!
b.js is: b.js 是:
var a = require('./../scenarios/a.js');
a.foo();
a.js is: a.js 是:
function foo() {
console.log('Hello World!');
}
module.exports = {
foo: foo
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.