How to get the object key and value from another javascript files

849 Views Asked by At

i am using $ npm run index.js

in index.js file i am looping and get list of below files, from the file we need to read the "testData", could you please help to get the data

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

each file having

/test/fileOne.js

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

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

My Code: 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////
    }
}

1

There are 1 best solutions below

0
On

You can read the content of the file as string using 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);
}