使用 Node js /javascript 中的 Promise 从 fs.readdir 返回值
function fileType() {
return new Promise((resolve, reject) => {
let Fields = fs.readdir(
path.resolve(__dirname, "access"),
(err, files) => {
if (err) {
reject(err);
return;
} else {
files.map((file) => {
return file.split(".").slice(0, -1).join(".");
});
}
}
);
resolve(Fields);
});
}
async function ambitious(data) {
let fields = [];
if (data.collections) {
fields= await fileType();
} else {
if(data.types.access){
fields.push(data.config.access);
}
else{
fields= await fileType();
}
}
return {
data_name: data.name,
data_access: data.config,
data_encrypted: data.encrypt,
data_fields: fields,
};
}
在这里,我尝试从 if 语句返回字段值并将其存储在 data_fields 中,
这里的问题是我从 else 语句获取值,但是当我尝试从 If 语句返回值时,它显示未定义,
因为我想阅读所有内容访问内存在的文件并删除文件扩展名,作为数组,我想将其存储在 data_fields 中,
例如,如果文件存在于访问内存中,
let files=[ 'config.sql','admin.xml', 'user_manual.txt' ]
出于此目的,我使用 split 和 slice 来删除所有扩展名并返回数组中的数据data_fields 中的格式
我没有知道如何从 fs.readdir 返回值并将其存储在 data_fields 中
function fileType() {
return new Promise((resolve, reject) => {
let Fields = fs.readdir(
path.resolve(__dirname, "access"),
(err, files) => {
if (err) {
reject(err);
return;
} else {
files.map((file) => {
return file.split(".").slice(0, -1).join(".");
});
}
}
);
resolve(Fields);
});
}
async function ambitious(data) {
let fields = [];
if (data.collections) {
fields= await fileType();
} else {
if(data.types.access){
fields.push(data.config.access);
}
else{
fields= await fileType();
}
}
return {
data_name: data.name,
data_access: data.config,
data_encrypted: data.encrypt,
data_fields: fields,
};
}
Here I am trying to return field value from the if statement and store it in the data_fields
here problem is I am getting the values from the else statement but when I am trying to return value from If statement its showing undefined
As I want to read all the files which are present inside the access and remove the file extension and as an array I want to store it in data_fields
for eg if files are present inside access
let files=[ 'config.sql','admin.xml', 'user_manual.txt' ]
for that purpose I used split and slice to remove all the extension and return data in array format in data_fields
I don't know how to return value from fs.readdir and store it in data_fields
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
Node 已经提供了
fs
API 的 Promise 版本。您不需要将回调版本包装在 Promise 中。Node already offers a Promise version of the
fs
API. You don't need to wrap the callback version in a Promise.尝试这样
Try like this