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?
Related
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
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.
I define this function a file like this, and immediately export it.
const watchMongo = () => {
console.log("foo")
};
module.exports = { watchMongo };
Then I import it and run it the main app, as shown here.
const watchMongo = require('./controllers/path');
watchMongo();
However, I get this error when ran. "watchMongo is not a function".
When I console log 'watchMongo' instead of running it, I'm told "{ watchMongo: [Function: watchMongo] }"
So Node sees and recognizes the function? Until the function needs to be ran? What??
You can do one of 2 things. You are defining watchMongo as a named export. You can either do:
const { watchMongo } = require('./controllers/path');
or on your declaration file export like:
module.exports = watchMongo;
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';
TL;DR There is some imported entity on ES6-module. Should find original ES module and line number, where this entity has been initially declared - not re-imported / re-exported.
There is some hierarchy of nested imported ES6-modules, some of which are not controlled by library code and had been imported from well-known place - it's some user-side configuration file.
Imagine following files structure:
config.js (not controlled)
import nested from './nested';
export default {
param1: { aaa: 10, bbb: 20 },
param2: nested
}
nested.js (not controlled)
export default {
ccc: 30,
ddd: 40
}
index.js (controlled)
import config from './config'
const ddd = config.ddd;
if(notValid(ddd)) {
const decl = %FIND_DECLARATION%(ddd);
console.log('Config variable "config.ddd" is not valid');
console.log('You declared it here: ', decl);
}
Output should be like following
You declared it here:
File webpack://./nested.js , line 2
ddd: 40
^^^^^^^
Should write function %FIND_DECLARATION%, which can find original ES-module and line number for some object declaration, and retrieve it's source code
Environment is webpack. Any dirty hacks are welcome if can't be solve without it.