-3

I'm new to js and I hardly use it. I'm more into java, but I have this little piece of code where I want it to return the content of the variable, which in turn brings the name of the file inside a folder, I need it to send it by mail and then move it from that folder, when I run the program it does not return the value of the field but an "undefined" when I run it sending it as a parameter of the function if it has a value, but I want that when listing this folder I return the value to work in a main function where it handles the other three functions (call file, send by mail, move it to another folder) I already have these three individually but I have the same problem that they return undefined

function listar(){
    var name;
fs.readdir("//URL/ConfirmadosPDF/", function (err, archivos) {
    if (err) {
    onError(err);
    return;
    }
    console.log(archivos[0]);
    
    if(archivos.length === 0){
        parar();
    }else{
        //enviarCorreo(archivos[0]);
        //moveFile(archivos[0]);

      name = archivos[0]
    }

    /*
    for (let index = 0; index < 10; index++) {
        const element = archivos[index];
        console.log(element)
    }*/
    
    });
   
return name
    
};

What I need is to do a succession of steps if the folder has files to send them by mail, but if not, if you send them, tell me if you sent it, and if I sent it, move it to a new folder, if it fails in any of these three steps would like to be able to handle it in a master function

2 Answers2

-1

This is an asynchronous function, the return runs first, than after a while a callback function is executed.

Try easier fs.readdirSync synchronous version.

Michał Moskal
  • 143
  • 2
  • 10
-1

First of all, does not existe de variable archivo.

I think you want to return the name.

And the path is wrong, You should use path.join

The func readdir is async

  • Sorry I have my code calling another function I edited it when I wrote the question but the variable is "name" – Kev Cordon Jan 17 '23 at 01:31
  • Please keep answers in English; it is a [requirement](https://meta.stackoverflow.com/questions/297673/how-do-i-deal-with-non-english-content). – Daedalus Jan 17 '23 at 01:37