gegner1111
gegner1111

Reputation: 25

fs-stat give value out - Node.js

my problem is that I want to have the processing time outside the fs-stat-function. How do I achieve this? With async that does not work, or how would you do that?

var time;
time = fs.stat(path, function(err, stats){  
  timestamp = stats.mtimeMs;
  console.log(timestamp); // 65463453
  return timestamp;
});

How can I get the result from the "function(err,stats)" of "fs-stat" in the variable "time"?

Upvotes: 1

Views: 658

Answers (2)

You can write code like this and call getTime function with promise and you will get the value.

var fs = require('fs');
function getTime(path) {
    return new Promise(function (resolve, reject) {
        fs.stat(path, function (err, stats) {
            if (err) {
                return reject(err)
            }
            return resolve(stats.mtimeMs);
        });
    })
}

call function like this

getTime('./').then(function (timestamp) {
    console.log(timestamp)
})

Upvotes: 1

gegner1111
gegner1111

Reputation: 25

@SayedTauseefHaiderNaqvi

This is the complete code:

function getTime(path) {

   var fs = require('fs');
   var time;
   time = fs.stat(path, function(err, stats){  
     timestamp = stats.mtimeMs;
     console.log(timestamp); //65463453
     return timestamp;
   });
   console.log(time); //undefined
   return time;
 }

Upvotes: 0

Related Questions