Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Nodejs path.resolve is not defined

// codenotworking

const path = require("path");
const fs = require("fs");
log = console.log;
const names = [];

function collectFileNamesRecursively(path) {
  fs.readdir(path, (err, files) => {
    err ? log(err) : log(files);

    // replacing paths
    for (const index in files) {
      const file = files[index];
      files[index] = path.resolve(path, file);
    }
    for (let file of files) {
      fs.stat(file, (err, stat) => {
        err ? log(err) : null;
        if (stat.isDirectory()) {
          collectFileNamesRecursively(file);
        }
        names.push(file);
      });
    }
  });
}
collectFileNamesRecursively(path.join(__dirname, "../public"));

i am using nodejs v10.8.0 and the directory stucture is

 - project/
 -     debug/
 -         codenotworking.js
 -     public/
 -        js/
 -            file2.js
 -        file.html

whenever i run this code i get the following error

TypeError: path.resolve is not a function at fs.readdir (C:\backup\project\debug\codenotworking.js:17:24) at FSReqWrap.oncomplete (fs.js:139:20)

what am i doing wrong here ?

like image 544
Karambit Avatar asked Aug 30 '26 19:08

Karambit


1 Answers

You're shadowing your path import by specifing the path parameter in collectFileNamesRecursively. Change the parameter name to something else.

Apart from that using recursion with callbacks this way won't work - I would recommend using async/await. Something like:

const path = require('path');
const fs = require('fs');

async function collectFileNamesRecursively(currBasePath, foundFileNames) {
    const dirContents = await fs.promises.readdir(currBasePath);

    for (const file of dirContents) {
        const currFilePath = path.resolve(currBasePath, file);
        const stat = await fs.promises.stat(currFilePath);
        if (stat.isDirectory()) {
            await collectFileNamesRecursively(currFilePath, foundFileNames);
        } else {
            foundFileNames.push(file);
        }
    }

}
like image 101
eol Avatar answered Sep 01 '26 09:09

eol



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!