从Node.JS事件而不是console.log返回值



我有下面的代码,它为给定的文件查找文件位置。我希望返回值,而不是console.log。用于查找文件位置的库-https://github.com/substack/node-findit

function searchfileloc(fname){
var finder = require('findit')(__dirname)
var path = require('path')
finder.on('file', function (file) {
if (path.basename(file) == fname){
console.log(file); //return file
finder.stop();
}
});
}

您可以将函数包装在Promise中,并使用await调用它以获得结果。

这里有一个例子:

function searchfileloc(fname) {
return new Promise((resolve, reject) => {
const finder = require("findit")(__dirname);
const path = require("path");
let found = false;
finder.on("file", (file) => {
if (path.basename(file) === fname) {
found = true;
finder.stop();
resolve(file);
}
});
finder.on("end", () => {
if (!found) {
reject(new Error("File not found"));
}
});
});
}
// Usage
const myFile = await searchfileloc("my_file_name");

最新更新