-1

I building a discord bot and I want to decleare a function in another file to keep my documents cleaner.

I have 2 files:

function.js

const needle = require("needle");

async function get() {
  const res = await needle("get", endpointURL, params, {
        headers: {
            "User-Agent": "v2LikingUsersJS",
            authorization: `Bearer ${token}`
        },
    });
     
    if (res.body) {
    return res.body;
    } else {
        throw new Error("Unsuccessful request");
    };
};

index.js

const imp = require("./function");

const data = await get();

If I run this code I get the error 'get is not a function'

I also tried:

"const data = await imp.get()";

Can anyone help me to get this running ? Thank for your help in advance.

N0rmal
  • 47
  • 1
  • 7
  • You have to export the function, then import/require it in the file you want to use it in. https://stackoverflow.com/questions/5311334/what-is-the-purpose-of-node-js-module-exports-and-how-do-you-use-it – Szabó Sebestyén May 16 '22 at 14:16

1 Answers1

2

Check out this link might help you out as exporting and importing is what you want https://www.tutorialsteacher.com/nodejs/nodejs-module-exports

I'd suggest using something like the following in your main file

import {yourFunction} from '/something.js';

and you can import multiple files and functions and then in your something.js if it was called that then you would add something like:

export myFunction() {
//code
}
moie
  • 66
  • 6