如何将文件路径保存到变量

时间:2020-08-09 01:12:01

标签: javascript node.js

我尝试过并查看了StackOverflow,而其他帖子都没有回答我的问题。这是一个独特的问题。我如何才能将最近上传的文件的路径保存到变量中,以便以后使用?

代码:

var pathtocheck = "C:\Users\user1\Downloads";


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


var getMostRecent = function (dir, cb) {
    var dir = path.resolve(dir);
    var files = fs.readdir(dir, function (err, files) {
        var sorted = files.map(function(v) {
            var filepath = path.resolve(dir, v);
            return {
                name:v,
                time:fs.statSync(filepath).mtime.getTime()
            }; 
        })
        .sort(function(a, b) { return b.time - a.time; })
        .map(function(v) { return v.name; });

        if (sorted.length > 0) {
            
            cb(null, sorted[0]);
    
        } else {
            cb('Y U NO have files in this dir?');
        

        }
    })
}

await getMostRecent(pathtocheck, function (err, recent) {
    if (err) console.error(err);
    console.log(recent);

});

var lastdownloadedimage = ;

1 个答案:

答案 0 :(得分:0)

使用回调,您必须在传递给getMostRecent的回调中编写代码,所以

// Note: awaiting this takes no effect unless getMostRecent returns a promise.
getMostRecent(pathtocheck, function (err, recent) {
    if (err) console.error(err);
    console.log(recent);

    var lastdownloadedimage = recent;
    // Or just directly use `recent`
});

或者,

异步等待和Promise也可以解决您的问题,尽管我不确定您对它们有多熟悉。

您可以通过require('fs').promises而非require('fs')(文档here)在Node.js v10或更高版本中使用文件系统API的承诺版本

像这样的功能的修饰:

// Also it's a good practice to use `const` or `let`, instead of `var`

const pathtocheck = "C:\Users\user1\Downloads";

const path = require('path');
const fs = require('fs');
const fsp = require('fs').promises;

// Decalre the function with `async` to use `await` in it
const getMostRecent = async function (dir) {
    dir = path.resolve(dir);
    const files = await fsp.readdir(dir)
    
    const sorted = files.map(function(v) {
        const filepath = path.resolve(dir, v);
        return {
            name:v,
            time:fs.statSync(filepath).mtime.getTime()
            // maybe you can use fsPromises.stat here
        }; 
    })
    .sort(function(a, b) { return b.time - a.time; })
    .map(function(v) { return v.name; });
        
    if (sorted.length > 0) {
        return sorted[0];
    } else {
        // Now you have no callbacks, so there are two options to return the error state.
        //   1. Throw an Error with an error message
        //   2. Return a special value such as `null` or `false`, which you can track it.
    }
}; // <-- perhaps you need place a semicolon here.

然后您在异步IIFE中调用该函数,将匿名异步函数包装为使用await

(async function() {
  const lastdownloadedimage = await getMostRecent(pathtocheck);
  console.log(lastdownloadedimage)
})();

或使用Promise.then

getMostRecent(pathtocheck).then(function(recent) {
    var lastdownloadedimage = recent;
    // Again, you can just directly use `recent`
})