Answer the question
In order to leave comments, you need to log in
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));
Answer the question
In order to leave comments, you need to log in
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));
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question