从远程js文件读取导出的变量 [英] Read exported variable from remote js file
本文介绍了从远程js文件读取导出的变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个需要阅读的javascript文件.我设法使用FileReader将其读取为字符串,但是我想读取在该文件中导出的对象.
I have a javascript file that I need to read. I managed to read it as a String using FileReader, but I want to read the object that is exported in that file.
这是我文件的外观:
const carsColor = {
audi: 'blue',
bmw: 'black',
};
export default carsColor;
将其读取为字符串:
loadFile = async () => {
try {
const response = await fetch(PATH_TO_FILE);
const blob = await response.blob();
let read = new FileReader();
read.onload = function() {
console.log(read.result); // read.result returns the entire file as a string
};
read.readAsBinaryString(blob);
}
catch(e) {
console.log(e);
}
}
是否可以从文件中获取carsColor对象?
Is there a way to get the carsColor object from the file?
谢谢.
推荐答案
更改文件以仅返回json并进行解析
Change your file to return only json and parse it
文件
{
audi: 'blue',
bmw: 'black',
}
加载功能
loadFile = async () => {
try {
const response = await fetch(PATH_TO_FILE);
const blob = await response.blob();
let read = new FileReader();
read.onload = function() {
console.log(JSON.parse(read.result));
};
read.readAsBinaryString(blob);
}
catch(e) {
console.log(e);
}
}
这篇关于从远程js文件读取导出的变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文