How to import an array file into a javascript file - javascript

I want to create a json file in brackets only to store an array that has 200 elements in it, and I want to be able to import that file into my "main.js" file, and be able to use it even though the array itself is not in "main.js" anymore.
How can I do this?

dummyData.js
export const data = [{}, ......, {}];
main.js
import { data } from './dummyData';
if you are using vanilla js, without es6 features, you could do the following:
//dummyData.js
module.exports = [{} ,........, {}];
//main.js
var data = require('./dummyData');

you should first export your json/array from a file
file should be something like
export const myJsonArray = [{...}, {...}, ...]
then in your main.js you can import the jsonArray like this
import myJsonArray from "{file_path}"

Create a JS file, say dataProvider.js, have your json defined as a constant, make it global write a function to convert it to JSON and return it, or just return the JSON as-is.
Now in your main.js include the dataProvider.js, and then you can access the shared variable.
Make sure that the page you're loading has both main.js and dataProvider.js imported.

Ok, here is sample:
In the demo we will load each object in array and create a paragraph.
Because snippet does not support multi files, the working demo is here:
https://repl.it/#PaulThomas1/DemoForTaho
Our HTML:
<div id="content"></div>
<script src="data.js"></script>
<script src="script.js"></script>
Our main javascript (script.js):
document.addEventListener("DOMContentLoaded", function() {
let contentDiv = document.getElementById("content");
let template = document.createElement("template");
data.forEach(dataItem => {
let element = document.createElement('p');
element.innerHTML = newPara(dataItem.name);
contentDiv.appendChild(element);
});
});
const newPara = (name) => { return `Name: ${name}` };
Our data lives in data.js :
data = [
{
"name" : "bert"
},
{
"name" : "bert11"
},
{
"name" : "bert22"
},
{
"name" : "bert33"
},
{
"name" : "bert44"
},
{
"name" : "bert55"
},
{
"name" : "bert66"
}
];

Step 1 :
add "export" keyword before anything you want to export.
ex- export const data = [{1,2,3}]
Step 2 :
add type="module" in html, where you link your js to html.
ex- <script src="index.js" type="module"></script>
Step 3 : add import keyword on top of the file where you want to import data.
ex- import { data } from './Data.js';

Related

require an array from a file javacsript

In a javacscript file I have something that looks like this,
module.exports = {
ROUTES: [
{"route1" : "route-1"},
{"route2" : "route-2"},
{"route3" : "route-3"}
]
}
I am doing the following to use these values in another file,
const routes = require("/routes");
meaning to access the values I have to do the following,
routes.ROUTES.route1
Is it possible to import the ROUTES array directly from the file so I can do,
ROUTES.route1
Since you're using common JS modules, you can use destructuring:
const { ROUTES } = require('./routes');
You could also export the routes array directly if you don't have anything else in the file:
module.exports = [
{"route1" : "route-1"},
{"route2" : "route-2"},
{"route3" : "route-3"}
]
That way you could keep your import:
const routes = require("/routes");

require or import in forEach loop

I have the following object:
const basePoints = {}
which I need to fill with json files. Currently I do:
import WH11 from 'assets/WH11';
const basePoints = { WH11}
I have like a dozen of such Json files but only 2-3 can be used at a given time. INstead of importing and loading all the JSON files i don't need, I want to require/import based on a config file as shown below:
and my config.js:
const config = {
basePoints: {
"WH11": "West Gate",
"WH12": "West Gate Back Drop"
}
}
WH11, WH12 etc basically exist in json format in my assets directory:
assets/basepoints/WH11.json
{
"startingID" : 198
}
etc. Now there can a dozen or more of such json files. The user just adds the ones to be used for the month in config.js.
Is there a way to require/import the json file based on the config file. The app can't compile if I do:
Object.keys(config.basePoints).forEach(key => {
basePoints[key] = require('../assets/basepoints/' + key + '.json');
});
the error is unexpected require().
You can use the latest ES2020 feature - Dynamic Import
Syntax -
import('/modules/<module_name>')
.then(module => {
//
})
.catch(err => {
//
});
You can learn more about it in this MDN document (scroll down to the dynamic import section) -
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/import

How to load an external js file and use their data in reactjs?

I'm doing a react project using create-react-app and my current goal is to load an external js file (that is hosted in iis) and use their data.
I'm getting this file throught a script in index.html like:
<script type="text/javascript" src="http://localhost:5000/GetJsFile"></script>
Example of my js file:
var data = {
vars: {
id: ****,
user ******,
name: *******,
date: *******,
}
//...
}
My question is: how can I use/access the data from js file inside a component of react js?
In your utils.js page
you must change your code to this shape:
utils page
const data = {
vars: {
id: ****,
user ******,
name: *******,
date: *******,
}
//...
}
export default data;
and after that in other component that you want to use this data write this code:
import data from '../../../../utils';
...
console.log('data', data);
The problem with loading the JSON's data from the html file directly is that it will not be available for your react code to use.
Since you are loading it from an external source, you need to use something like fetch, axios or superagent to retrieve it.
You can either use async/await or promises.
async function loadJsonFromExternal() {
const dataFromJSON = await axios.get('http://localhost:5000/GetJson');
return dataFromJSON;
}
Say you have your component.js file with something like this:
import React, { useEffect } from 'react';
export default function CoolComponent (props) {
let myName = 'Enigma';
useEffect(() => {
loadJsonFromExternal()
.then((result) => { myName = result.name });
}, [])
return (
<div>My name is: {myName}</div>
)
}
That would be the approach to do.

Read contents of file into array inside vue component

Inside my media.txt file, I have:
"https://www.dropbox.com/s/******/687.jpg?dl=0",
"https://www.dropbox.com/s/******/0688.jpg?dl=0
I have the following Vue carousel component:
<template>
<section>
<v-card
class="mx-auto"
color="#26c6da"
dark
max-width="1200"
>
<v-carousel>
<v-carousel-item v-for="(item,i) in items" :key="i" :src="item.src"></v-carousel-item>
</v-carousel>
</v-card>
</section>
</template>
<script>
var cache = {};
// const images = require.context('../static/', false, /\.png$|\.jpg/);
// const images = require.context('../static/', false, /\.png$|\.jpg|\.mp4/); // WORKING
const images = require.context('../static/media.txt', false, /\.png$|\.jpg|\.mp4/);
var imagesArray = Array.from(images.keys());
// const images = ["./52lv.PNG", "./Capture1.PNG", "./maps.PNG"]
console.log(images.keys());
console.log('images');
console.log(images);
var constructed = [];
function constructItems(fileNames, constructed) {
fileNames.forEach(fileName => {
constructed.push({
'src': fileName.substr(1)
})
});
return constructed;
}
console.log('items ');
console.log(imagesArray);
// At build-time cache will be populated with all required modules.
var res = constructItems(imagesArray, constructed);
console.log(res);
export default {
data: function() {
return {
items: res
};
}
};
</script>
I want to read the images from the media.txt file into an array, then populate the carousel src with these. I've been trying with Webpack's require.context function, but I'm getting a module not found error.
How can I get this working?
It looks like you're trying to import a string array (JSON) into a variable. That string array should be delimited by square brackets like this:
[
"foo",
"bar"
]
require.context(dirPath, useSubDirs, filenameRegex) is not the appropriate API to use here, as that method imports multiple files from a specified directory. For instance, the code below tells Webpack to load *.png, *.jpg, and *.mp4 files from the directory named ../static/media.txt (which presumably is actually a file).
require.context('../static/media.txt', false, /\.png$|\.jpg|\.mp4/) // DON'T DO THIS
Instead, you could simply use require('path/to/file.json') to import the specified file as a JSON object/array. For example, to import src/assets/media.json (containing the array mentioned at the top), the syntax would be:
// e.g., in src/components/Foo.vue
const media = require('../assets/media.json')
console.log(media) // => [ "foo", "bar" ]
demo
You probably should install https://github.com/webpack-contrib/raw-loader#getting-started (a loader for webpack read txt files), configure it in your vue.config.js and you should be able to import like this: import txt from 'raw-loader!./file.txt'; instead using require.

Importing data object from file-to-file

I have a .JSON (named dataOut.json) file that looks similar to the following:
[
{
"scan_type": "nexpose",
"date_time": "2011-07-18 11:11:11",
"source_address": "1108",
"source_lat": "40.581160",
"source_lng": "-105.184110",
"dest_address": "11.166.181.0",
"dest_lat": "30.003880",
"dest_lng": "-604.800360"
},
...
]
I have a script that seperates the source/destination data points, and places the output in separate files, here is my code for doing so.
So here is my problem, I need to export the object variable "scan_type" from the code above, to another .JS file, named jsontonbh.js .
I tried using module exports:
//exporting 'scan_type'
obj.forEach(block => {
...
module.exports = {scan_type:block.scan_type};
...
});
and then importing it in my jsontobh.js file by requiring it, as shown here:
let sourceFile = require('./jsonParents.js');
obj.forEach(block => {
console.log(sourceFile.scan_type)
});
this code returns the error "Unexpected end of JSON input"
How can I export this variable scan_type from my first script, to my second script?

Categories