'Accesing a function in another file [duplicate]

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.



Solution 1:[1]

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
}

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 moie