0

Learning how to develop modules I'm trying to learn how to export one from main.js. On my renderer I can send it correctly to main with:

renderer.js:

let _object = {
    foo: foo1,
    bar: bar1,
}
ipcRenderer.send('channel', _object)

in main.js I can get this correctly:

ipcMain.on('channel', (e, res) => {
  console.log(JSON.stringify(res))
  console.log(typeof res)
})

however when I export the result from main.js and try to bring it into another file I get an undefined:

main.js:

const foobar = require('./foobar')

ipcMain.on('channel', (e, res) => {
  console.log(JSON.stringify(res))
  console.log(typeof res)

  module.exports.res = res
  foobar.testing()
})

foobar.js:

const res = require('./main')

module.exports = {
    testing: function(res) {
        console.log(`Attempting console.log test: ${res}`)
        console.log(res)
        console.log(JSON.stringify(res))
    }
}

terminal result:

Attempting console.log test: undefined 
undefined
undefined

I've also tried to redefine the object in main.js:

ipcMain.on('channel', (e, res) => {
  module.exports =  {
        foo: foo,
        bar: bar,
    }
  console.log(`Testing object ${res.foo}`)

  foobar.testing()
})

My research of reference:

What a I doing wrong in my export of the result in main.js so I can use it in a different file?

Edit:

My end goal is to learn how to be able to call res.foo in foobar.js.

DᴀʀᴛʜVᴀᴅᴇʀ
  • 7,681
  • 17
  • 73
  • 127
  • Well first of all, you're printing `res` from arguments, which is undefined and shadows the imported variable. – riv Apr 19 '19 at 15:46
  • So what is the proper way to restructure that in *main.js*? – DᴀʀᴛʜVᴀᴅᴇʀ Apr 19 '19 at 15:47
  • Best way would be to just pass `res` as an argument to `testing` instead of using exports, but if you specifically want to use exports you'd just need to remove the argument from `testing` declaration. However I don't think that would help, because the `require` statement would snapshot the initial export, so you'd have to export an empty object and put the `res` in there. – riv Apr 19 '19 at 15:48

1 Answers1

1

First of all, you have an argument res in your testing function, which shadows the import. Second, the imported res object is all exports from main, which includes the res you need - so you should print res.res instead of the whole object.

Foobar.js:

const res = require('./main')

module.exports = {
    testing: function() {
        console.log(`Attempting console.log test: ${res.res}`)
        console.log(res.res)
        console.log(JSON.stringify(res.res))
    }
}

The last version (where you reassign module.exports) would not work, because foobar will still have the original exports, which was an empty object.

riv
  • 6,846
  • 2
  • 34
  • 63