简体   繁体   中英

calling a function in another file in javascript using node.js

I have a problem, i am trying to create an object that i can use over and over in a separate javascript file. I have a file called foo.js and another file called boo.js. I want to create the object in boo.js In my server.js file i required foo.js, and it works fine i can access foo.js. I want to be able to access boo.js from foo.js. I keep getting errors when i require boo.js in foo.js and i cant access it. Is There a way to do this?

here is my code

//boo.js
var obj = function () {
   return {
     data: 'data'
  }
}

module.exports = {
  obj: obj
}

foo.js

//foo.js

var request = require('request');
var x = require('./modules/boo')
var random= function() {
    return x.obj();
}

module.exports = {
  random: random
}

If they are in the same directory you will want to require like so var x = require('./boo') . The ./ is relative to the current directory.

they are both in the same directory

In that case, you'll want to remove the modules/ from the path:

var x = require('./boo');

require() is aware of the current script's location and bases relative paths from the script's own parent directory.

The ./ at the start of the path will refer to the same directory as __dirname , which seems to be modules/ .

console.log(__dirname);
// "/project-path/modules"

Including modules/ in the path will result in doubling it:

var path = require('path');

console.log(path.resolve(__dirname, './modules/boo'));
// "/project-path/modules/modules/boo"

(Side note: The fs module does not behave the same way. Relative paths for it are based from the current working directory or process.cwd() .)

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