If there is a java script file with some functions and some variables and another java script file that wants to access them or use them in what way can it do that?
I have a js file with something like lets say
const info = {
get: function(){
console.log("Getting information")
}
}
And now lets say i want to call that function in my other js script:
info.get()
Yet it does not seem to work as some pointed out it may be because the first script is ran after the second one so that may be the problem.
Im using node.js and js to run my program.
Another way i could do that is manually which is to convert the script into a string with
fs.readfileSync("The path to the script");
then find each line that contains it and then run a function. That might work but it will not be as great when there are variables involded into the mix. Thats why im asking if there is another, more suitable for long term use way?
As i mentioned it may be because the first script is ran after the second one, and if thats so... how can i make the run before that in the actual project itself? I could combine it into one whole script but that basically defeats the entire point of my question which is.. is there a way i can access them in a seperate file?
Could i require it like a library?:
const firstScript=require("path to first script");
Again it doesn't seem to function like that. I tried googling it but nothing popped up, everything was just html.
I told you a couple of ways i tried doing things, but if anyone finds a better more suitable way of doing things rather than just .slice .indexOf, manual way please do tell me, i would love to hear what you found
Could i require it like a library?:
const firstScript=require("path to first script");
Yes, exactly, with a relative path.
For instance, for your info object, you might export it like this:
// ESM:
export const info = /*...*/;
// Or the older CommonJS
exports.info = /*...*/;
then import it like this if the files are next to each other in the same directory:
// ESM
import { info } from "./firstScript.js";
// Or the older CommonJS
const { info } = require("./firstScript.js");
So for instance, if the files are next to each other in the directory:
In the ESM part of that example I've used a named export (there's also a default export). When importing a named export, you put the name in { } (possibly along with others that you want to import, comma-separated). (Despite the superficial resemblance to destruturing, import syntax is not destructuring syntax; it's just a superficial resemblance in that one particular way.)
Read about modules here (for ESM) and here (for CommonJS).