How would I import a function into my index.js

I’m very new to Javascript - what I’m trying to do is use a function within another Javscript file. However When I attempt to do this its giving me a typeError. Can anyone help me with this?

In my commands.js file I have the following function:

function startServer()
{
  const { net } = require('electron')
  const request = net.request('https://fire.qa.local')
  request.on('response', (response) => {
    console.log(`STATUS: ${response.statusCode}`)
    console.log(`HEADERS: ${JSON.stringify(response.headers)}`)
    response.on('data', (chunk) => {
      console.log(`BODY: ${chunk}`)
    })
    response.on('end', () => {
      console.log('No more data in response.')
    })
  })
  request.end()
}

I am trying to call this from inside of my index.JS file:

const commands = require('./commands');

app.whenReady().then(() => {
commands.startServer();

})

Can someone explain what im doing wrong? I’ve come from C# and javascript just seems way more complicated when it comes to importing functions.

Thankyou!

First of all require is no standard JavaScript command but a node.js enhancement.

So if you are not using node.js you must include your other script file with a script tag in the HtmlDOM or load it into it dynamically

var script = document.createElement('script');
script.src = something;
//do stuff with the script

Nevertheless require only works with modules not with scripts. So you need to define a class and export it into your command file when you want to go that way

  1. Always state that you’re talking about Electron - that’s important to know;
  2. Show complete error message if you want to get help. We have no idea what’s wrong now.

Seems like you just need to add export at the end of your commands.js

module.exports = { startServer }

Hi,

I’m assuming you are aware of the differences between ES modules and CommonJS modules.

To make your example work, you need to export the startServer function, so that it is accessible to other files. You can do so like this:

commands.js

function startServer() {
  console.log('The server has started');
}

module.exports = { startServer };

index.js

const commands = require('./commands');
commands.startServer();

Start the script with node index.js and this will log “The server has started to the console”.

You can read more about module.exports here.

1 Like

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.