2

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?

3 Answers 3

1

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.

Sign up to request clarification or add additional context in comments.

Comments

1

Within a.js:

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

Then in b.js:

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

Comments

0

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
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.