george.angelop
george.angelop

Reputation: 45

Undefined value when using fs.writeFile

I am using node.js and i am trying to read a folder and return the file.length, then i want to write the value on a txt file. The problem is that when i try to use fs.writeFile it creates a file that only contains the world undefined .

var length;
fs.readdir(dir, function(err, file) {
   length = file.length+1;
});
setTimeout(function(){
}, 1000);  
fs.writeFile('/public/images/value.txt', length, function(err) {
     if(err) {
        return console.log(err);
       }

     console.log("The file was saved!");
     console.log(length);
});

console.log(length) returns 6

Upvotes: 2

Views: 5394

Answers (2)

jfriend00
jfriend00

Reputation: 707318

You have some errors in your you're handling asynchronous code. Both fs.readir() and fs.writeFile() are asynchronous. That means, the only way you know they are done is inside their callback.

fs.readdir(dir, function(err, files) {
    if (err) return console.log(err);
    let length = files.length + 1;
    fs.writeFile('/public/images/value.txt', length, function(err) {
        if(err) return console.log(err);
        console.log("The file was saved!");
        console.log(length);
    });
});

// fs.readdir() has not yet completed when this part of your code runs
// it will complete some time late and then call its callback
// similarly fs.writeFile() has not yet completed when this part of your code runs

So, if you want to use the result of fs.readdir(), then you should use it inside the callback. If you want to know when fs.writeFile() is done and to count on its presence and being up-to-date, you can only do that in its callback.

In addition, setTimeout() is NOT blocking. All it does is schedule a timer to fire sometime in the future while the rest of your code keeps running. So, if you were going to use a setTimeout() here, you'd have to put the fs.writeFile() code inside the setTimeout() callback. But, that's a hack and is not the recommended way to handle asynchronous code. You should just put the fs.writeFile() inside the fs.readdir() callback and then things will be 100% reliable.

Asynchronous results MUST be used inside the actual callback that signifies completion of the async operation or in a function that you call from within that callback.

Upvotes: 3

Alfon
Alfon

Reputation: 11

This a typical error when you´re dealing with asynchronous code. The reason why you´re getting undefined is because the first function hasn´t finished reading the directory when the fs.writefile function is executed, so at this time length is still undefined. Try putting the writefile function inside your setTimeout function. This should make it.

Upvotes: 0

Related Questions