X
X
Xenia2018-08-28 20:54:08
recursion
Xenia, 2018-08-28 20:54:08

Why does a function in node.js return undefined?

just starting to learn node and async, writing a function that will recursively look for a package.json file and return the path where it finds it.

function getRoot(startPath) {
        let isRoot = false;
        if (isRoot) {
            return startPath
        }

        fs.access(`${startPath}/package.json`, fs.constants.F_OK, (err) => {
            if (!err) {
                isRoot = true;
            } else {
                const arr = startPath.split('/');
                arr.pop();
                const newRoot = arr.join('/');
                return getRoot(newRoot);
            }
        })
    }
    console.log(getRoot(process.env.PWD));

Undefined is returned to me, although if it is consoled, then the function is called every time with the expected startPath and stops as it should. I don't understand where is wrong?

Answer the question

In order to leave comments, you need to log in

2 answer(s)
S
Stockholm Syndrome, 2018-08-28
@TGNC

try like this:

async function getRoot(startPath) {
    return new Promise(async (resolve, reject) => {
        fs.access(`${startPath}/package.json`, fs.constants.F_OK, (err) => {
            if (!err) {
                resolve(startPath);
            } else {
                const arr = startPath.split('/');
                arr.pop();
                const newRoot = arr.join('/');
                resolve(await (getRoot(newRoot)));
            }
        });
    });
}
getRoot(process.env.PWD).then((data) => console.log(data));

R
RidgeA, 2018-08-28
@RidgeA

callback

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question