我希望我的方法生成一个表示目录树的js对象,我使用directory-tree:https://www.npmjs.com/package/directory-tree。 而且很管用。
我的问题是,当我想计算视频文件(MP4)的持续时间时,我想给每个项目添加一个属性“duration”,但是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"
}
...
您可以在承诺字符串中添加一个中间动作,然后投掷树查找视频。 是这样的:
getCourseVideos('/PATH/TO/YOUR/FOLDER/OF/VIDEOS')
.then(async (tree)=> {
const queue = [tree];
while (queue.length > 0) {
const item = queue.shift();
if (item.children) {
for (let it of item.children) {
queue.push(it)
}
} else if (item.type === 'file') {
item = await anAsyncMethod(item.path);
}
}
return tree;
})
.then(tree => console.log(tree));
我找到了一个解决方案:这是新代码
const {getVideoDurationInSeconds} = require('get-video-duration');
const dirTree = require("directory-tree");
async function getVideoDuration(path) {
const duration = await getVideoDurationInSeconds(path);
return duration;
}
const recursiveAsync = async (item, PATH, stats) => {
if (item.type === 'directory') {
item.children = await Promise.all(item.children.map(async (item) => {
return recursiveAsync(item);
}));
}
if (item.type === 'file' && item.extension === '.mp4') {
const duration = await getVideoDuration(item.path);
item.duration = duration;
}
return item;
}
const getCourseVideos = async (path) => {
const tree = dirTree(path, {extensions: /\.mp4/,});
await Promise.all(tree.children.map(async (item) => {
return recursiveAsync(item);
}));
return tree;
};
getCourseVideos('/PATH/TO/YOUR/FOLDER/OF/VIDEOS').then((tree) => {
console.log(tree);
});