Search code examples
javascriptnode.jsfunctionreturn

How do I return a result in a file finding function (Node.js)?


Using Node.js, I'm trying to search in the current directory for a specific file with a random number appended at the end of the filename. After some searching online I found this package would probably be best for the job, but I can't seem to make it work.

This is what I have so far:

const find = require('find');

function func1() {
    const x = find.file(/solution[0-9]*\.json/, __dirname, function(files) {
        console.log(files[0]);
        return files[0];
    });
    console.log(x);
}

func1();

This does a great job at finding the correct file and printing it to the console, but I still can't use the path to that file in func1, which is what I needed. This is the result I get:

{ error: [Function: error] }
C:\Users\dir1\dir2\solution78029853.json

I've tried multiple 'experimental' possible syntaxes but none of it seems to work and this is really the closest I can get. I did notice that the { error: [Function: error] } is displayed before the console.log(files[0]);, but I'm not really sure if that's the problem and if it is, I don't know how I can prevent it. Without the const x = and the console.log(x); I get no error, and only the path is displayed, so I'm sure something with that is wrong; I just don't know what. I've been searching the web for over an hour now with no progress so hopefully someone knows what (probably simple) thing I've been doing wrong.

Edit of func1() after Bergur's comment:

function func1() {
    const x = find.file(/solution[0-9]*\.json/, __dirname, function(files) {
        console.log(files[0]);
        return files[0];
    })
    .error(function(err) {
        if (err) {
            //
        }
    });
    console.log(x);
}

This doesn't produce the error, but just prints undefined instead for console.log(x);.


Solution

  • The function find.file is asynchronous meaning that you will get the results in a callback (third argument of that function). Assuming you are using ES6 and want to avoid the callback hell problem, you could use async and await like this:

    const find = require('find');
    
    async function findFile(name, path) {
      return new Promise(function (ok, fail) {
        find.file(name, path, function(files) {
            ok(files.find(_ => true)) // resolve promise and return the first element
        });
      });
    }
    
    async function func1() {
        const x = await findFile(/testFile[0-9]/, "files")
        console.log(`Path to my file: ${x}`);
    }
    
    func1();
    

    Link: https://repl.it/repls/ZestyJauntyApplicationserver