1

I am new to node.js. I have the following code

module aws.js
  ....
  const awssvc = { dynamoQuery }
  module.exports = { awssvc }

module A.js
  const { awssvc } = require( ./index )
  ....
  module.export = { a }

module B.js
  const { awssvc } = require( ./index )
  ....
  module.export = { b }

index.js
const { awssvc } = require('./aws');
const { a } = require('./A');
const { b} = require('./B');

module.exports = { awssvc, a, b} 

In A.js when executing awssvc.dynamoQuery, I got TypeError: Cannot read property 'dynamoQuery' of undefined.

What have I missed?

Or what should or should not go into index.js?

Shawn
  • 5,130
  • 13
  • 66
  • 109
  • It looks like you're missing an equals sign after the deconstruction, `const { awssvc } require( ./index )` should be `const { awssvc } = require( ./index )`. Same thing goes for the `module.export { a }` should be `module.exports = { a }` – Lawrence May 08 '19 at 21:18
  • I have the `=` in my actual code. just edited the post. sorry – Shawn May 08 '19 at 21:20

1 Answers1

1

Make sure you have equals signs for the deconstruction assignments

const { awssvc } require( ./index ) should be const { awssvc } = require( ./index )

Also, change module.export { a } to module.exports = { a }

It also looks like you're trying to import awssvc from the index.js file, it should be requiring from aws.js, So in module A.js const { awssvc } = require(./index) should be const { awssvc } = require ('./aws.js')

Lawrence
  • 327
  • 1
  • 12
  • I changed in module A.js from `const { awssvc } = require(./index)` to `const { awssvc } = require ('./aws.js')`. and it worked. Can you help explain why I cannot require from index.js? – Shawn May 08 '19 at 21:26
  • 1
    What you had before is a circular dependency, module A.js requires index, but index also requires A.js, [this post](https://stackoverflow.com/questions/10869276/how-to-deal-with-cyclic-dependencies-in-node-js) goes a little more in-depth about it – Lawrence May 08 '19 at 21:31