简体   繁体   中英

local modules node.js :can't load files other than index.js

I am trying to learn local module setup in my express js application.

test-module folder is created in my project folder and it contains two files

1)index.js

 module.exports = {

      indexfunc:function(){
       console.log('ok from index');
     }


  }

2)hello.js.

 module.exports = {

  helloFunc:function(){
     console.log('ok from hello');
  }

}

importing this module in app.js file

   var mymodule = require('hello-module');
    console.log(mymodule);

   output:{ indexfunc: [Function: indexfunc] }

But this returns console.log(require('hello-module').hello) undefined .

package.json for this module

{
  "name": "hello-module",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "author": "",
  "license": "ISC"
}

Since hello is a file in hello-module , you need to pass it as the path to require . Do:

console.log(require('hello-module/hello'))

By doing :

console.log(require('hello-module').hello)

You are printing the hello property exported by index.js

I addition to @Ayush answer, if your goal is to execute code from other files in a module folder you can export a reference like so :

//index.js

const helloModule = require('./hello');

module.exports = {
      hello: helloModule,
      indexfunc:function(){
       console.log('ok from index');
     }
}

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