Rayrun
← Back to Discord Forum

How to read loacl files in tests

We have a project setup in which we have config.json file whcih is located in multiple subdirs as it is for basic configurations. So we want to read the content of this config.json file from our project dir, where are trying to use glob package which allows us to define a path like this '../../../main/samples/src/**/config.json' so how we can do that from test?

We tried to setup it like this but that doen't work and throws following error import util from "util"; import {glob} from "glob";

const globAsync = util.promisify(glob); const matches = await globAsync(path.resolve(__dirname, ''../../../main/samples/src/**/config.json''), {nodir: true}); console.log("Matches", matches);

This thread is trying to answer question "How can I read the content of a config.json file located in multiple subdirectories from my project directory using the glob package in a test?"

2 replies
refactoreric

I think something got messed up in the formatting due to the double asterisk in the glob probably.

And I don't see the error that is thrown.

refactoreric

Looking at the examples from here: https://www.npmjs.com/package/glob

You should not need util.promisify.

Answer

Sure, let's dive right in! First, you'll need to install the glob package. Run npm install glob in your project's directory.

npm install glob

Now, you're ready to use glob in your test file. Here's a quick example:

import * as fs from 'fs';
import * as glob from 'glob';

const pattern = '**/config.json';

glob(pattern, (err: Error | null, files: string[]) => {
  if (err) {
    console.error('An error occurred:', err);
    return;
  }

  for (const file of files) {
    try {
      const content = fs.readFileSync(file, 'utf8');
      console.log(`Content of ${file}:`, content);
    } catch (error) {
      console.error(`Error reading ${file}:`, error);
    }
  }
});

In this code, **/config.json matches all config.json files in any subdirectory. We then read and log the contents of each file. Remember to handle any errors that might occur!

This is a basic example, but it should help you get started with reading config.json files in multiple subdirectories using glob. Happy coding!

Related Discord Threads

TwitterGitHubLinkedIn
AboutQuestionsDiscord ForumBrowser ExtensionTagsQA Jobs

Rayrun is a community for QA engineers. I am constantly looking for new ways to add value to people learning Playwright and other browser automation frameworks. If you have feedback, email [email protected].