1

I am writing an API in NodeJS and I have ran into a brick wall. I am trying to use a function to grab a variable and use module.exports to use said variable in another file. This however keeps coming up as undefined in the console.

I have already tried used return statements in different places in the file but I keep getting undefined.

This is what the code looks like to grab the variable and export it.

File 1 (api.js)

const fs = require('fs');
const homeDir = require('os').homedir();
module.exports = {
    workingDirectory: () => {
        let dir;
        fs.access(`${homeDir}/.unitv`, fs.constants.F_OK, (err) => {
            if(err) throw err;
            fs.readFile(`${homeDir}/.unitv`, 'utf8', (readErr, data) => {
                if(readErr) throw readErr;
                let jsonData = JSON.parse(data);
                dir = jsonData.WorkingDirectory;
            });
        });
        return dir;
    }
};

File 2

const api = require('../api');
console.log(api.workingDirectory);

.unitv file

{
    "WorkingDirectory": "/home/user/UniTV",
    "Port": "3000"
}

In the console it will turn up as undefined when it should turn up with the value of the "working directory" in /home/user/.unitv

Any and all help is appreciated, thanks.

1 Answers1

0

Your current code is particularly problematic. return dir; occurs before fs.access/fs.readFile finishes. These are asynchronous functions and require the use of callback, promise, or async/await styled coding. The gist of it is that the code continues executing other code while it waits on I/O (such as reading a file) and the way you have written it causes nothing to be returned. See https://repl.it/@CodyGeisler/readFileCallback for a working callback example.

workingDirectory: () => {
    let dir;
    fs.access(`${homeDir}/.unitv`, fs.constants.F_OK, (err) => {
        if(err) throw err;
        fs.readFile(`${homeDir}/.unitv`, 'utf8', (readErr, data) => {
            if(readErr) throw readErr;
            let jsonData = JSON.parse(data);
            dir = jsonData.WorkingDirectory;
        });
    });
    return dir;
}
Cody G
  • 8,368
  • 2
  • 35
  • 50