-1

The issue is that I'm trying to write a javascript file that can execute several js files, but I cannot make it to work.

Is there a way to call and execute a js file in another js file? For example:

function callJsFile()
{
//call a .js file and execute the code in it at ../js/somejavascript.js"
}

I have tried exporting the result variable that I need from a js file, and run it on the Main Javascript file, but it returns "undefined", because you actually need to run the js file in order for you to get the result on the variable.

module.exports.post = post_db_01; 
  • If import/export isn't working, you will likely have to show us the real code in the imported file for us to help who you what's wrong with that code. And, if you have asynchronous operations to get the result, you can import an asynchronously received value (the import finishes before the value is ready). You can import a promise and use `.then()` on the promise to get the value when it's ready. – jfriend00 Feb 08 '19 at 18:01

2 Answers2

1

Are you using Node or web JS?

Web JS you can just export { someFile } and then when you import it, in another file you do: import { someFile } from './someFile'

For Node you need to do the module exports and then import using require, so you would do const someFile = require("./someFile.js")

ehutchllew
  • 940
  • 8
  • 14
  • Sound great, but I have a question about what you explained. When you use the export modules and then import them using require, does that mean that the javascript code on the export modules runs beforehand? Because otherwise it will return undefined. – Gio González Feb 08 '19 at 18:27
  • You would have to invoke the functions you are exporting. So you could do something like `const someFile = require("./someFile.js");` and then do `someFile.method()` – ehutchllew Feb 08 '19 at 19:03
0

let's say you have function A in file 1 and you need to use this function in file 2 So : file 1 :

 exports.A = function A(){

})

while in file 2 :

import {A} from './file1.js'