简体   繁体   中英

importing and running functions from javascript files with node

I have a simple javascript question. I have two files, a.js and b.js defined in the same directory.

Within a.js I define a function:

function foo() {
console.log('Hello World!');
}

in b.js I have:

var a = require('./../scenarios/a.js');
a.foo();

However, when I run node b.js, I get:

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 :

function foo() {
console.log('Hello World!');
}

exports.foo = foo;

You should then be able to access it in b.js .

Within a.js :

module.exports = {
    foo: function() {
        console.log('Hello World!');
    }
}

Then in b.js :

var a = require('./scenarios/a.js');
a.foo();

I was able to figure this out! module.exports needs to be defined. Ah the joys of learning JavaScript from the beginning!

b.js is:

var a = require('./../scenarios/a.js');
a.foo();

a.js is:

function foo() {
    console.log('Hello World!');
}

module.exports = {
    foo: foo
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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