Home > Enterprise >  How to fetch data from another javascript file
How to fetch data from another javascript file

Time:04-14

I am trying to use the fetch API and async await to fetch an array in another file and use it in a separate js file.

For example:

data.js app.js

I am working within app.js and would like to use the data (in an array) from data.js

data.js looks like this:

//data.js
const data = ['steve','jim','julie']
//app.js
const res = fetch('./data.js')
const data = res.data

I seem to be unable to read the data variable from data.js into app.js.

CodePudding user response:

It looks like you want to do javascript import

// module "my-module.js"

export default function cube(x) {
  return x * x * x;
}


// another file.js

import cube from './my-module.js'
console.log(cube(3)); // 27

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/export

CodePudding user response:

To export the data, use export:

export const data = ['steve','jim','julie'];

then import it in your main file and display it:

const your_export = require('./modules');
let {  data } = your_export
console.log(data)

You can read more about it here

  • Related