【问题标题】:How to get the object key and value from another javascript files如何从另一个 javascript 文件中获取对象键和值
【发布时间】:2020-05-09 03:54:22
【问题描述】:

我正在使用 $ npm run index.js

在 index.js 文件中,我正在循环并获取以下文件的列表,从我们需要读取“testData”的文件中,请您帮忙获取数据

var listOfFiles = ['test/fileOne.js',
,test/example.js,]

每个文件都有

/test/fileOne.js

var testData = {
    tags: 'tag1 tag2 tag3',
    setup: 'one_tier'
}
/test/example.js

var testData = {
    tags: 'tag3',
    setup: 'two_tier'
}

我的代码:index.js

let fs = require("fs")
const glob = require("glob");

var getDirectories = function (src, callback) {
    glob(src + '/**/*.js', callback);
};
getDirectories('tests', function (err, res) {
if (err) {
    console.log('Error', err);
} 
else {
    var listOfFiles = res;
    for (let val of listOfFiles){
       ///// HERE we have to get the Tags and setup from each js file////
    }
}

【问题讨论】:

  • 可以在每个file_x.js的末尾加上export {testData},用import test1 from test_1.js导入,作为test1.testData使用
  • 如果你不能修改test_xx.js文件来导出数据,那么你必须将文件读入mmeory和eval()它们,然后引用它们产生的testData变量在你的范围内。
  • @ChristhoferNatalius 我们无法导入特定文件,它在测试文件夹中的动态文件 for (let val of listOfFiles){ ///// 这里我们必须从每个 js 文件中获取标签和设置//// }

标签: javascript node.js cypress glob acorn


【解决方案1】:

您可以使用fs.readFileSync 将文件内容作为字符串读取:

for (const val of listOfFiles) {
    ///// HERE we have to get the Tags and setup from each js file////
    const content = fs.readFileSync(val, 'utf8');
    console.log(content);
    const tags = content.match(/tags: '(.*?)'/)[1];
    console.log(tags);
    const setup = content.match(/setup: '(.*?)'/)[1];
    console.log(setup);
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-08-03
    • 1970-01-01
    • 2014-10-13
    • 1970-01-01
    • 1970-01-01
    • 2019-04-03
    • 2021-11-19
    • 2018-09-12
    相关资源
    最近更新 更多