【发布时间】:2020-09-26 09:25:06
【问题描述】:
我希望我的方法生成一个表示目录树的 js 对象,我使用目录树:https://www.npmjs.com/package/directory-tree。并且有效。
我的问题是何时我想计算视频文件 (MP4) 的持续时间 我想为每个项目添加一个属性“持续时间”,但 id 不起作用,因为它返回一个承诺。
我使用 get-video-duration 来计算持续时间:https://www.npmjs.com/package/get-video-duration
这里是代码
const {getVideoDurationInSeconds} = require('get-video-duration');
const dirTree = require("directory-tree");
async function getVideoDuration(path) {
const duration = await getVideoDurationInSeconds(path);
return duration;
}
const anAsyncMethod = async (item, PATH, stats) => {
if (item.type === 'file' && item.extension === '.mp4') {
const duration = await getVideoDuration(item.path);
item.duration = duration;
console.log(item); // it works here
return item;
}
}
const getCourseVideos = async (path) => {
const tree = await dirTree(path, { extensions: /\.mp4/,} , anAsyncMethod);
return (tree);
};
getCourseVideos('/PATH/TO/YOUR/FOLDER/OF/VIDEOS').then((tree)=> {
console.log(tree);
});
实际输出示例:
{
"path": "/MY/PATH/HERE",
"name": "react",
"children": [
{
"path": "/MY/PATH/HERE/lesson",
"name": "lesson",
"children": [
{
"path": "/MY/PATH/HERE/lesson/lesson10.mp4",
"name": "lesson10.mp4",
"size": 38642184,
"extension": ".mp4",
"type": "file"
},
{
"path": "/MY/PATH/HERE/lesson/lesson11.mp4",
"name": "lesson11.mp4",
"size": 41421609,
"extension": ".mp4",
"type": "file"
}
}
],
"size": 17042089152,
"type": "directory"
}
...
【问题讨论】:
标签: javascript node.js promise async-await