提问者:小点点

对象中的JavaScript等待


我想把项目目录中的文件和文件夹转移到带有节点的对象中,我想把“根”文件夹定义到像“树视图”这样的对象中,但是,它被记录为“挂起”,可以帮我解决这个问题吗?

根文件夹屏幕快照

根文件夹/资产屏幕截图

我的NodeJS代码:

import path from 'path';
import {program} from 'commander';
import fs from 'fs';
import util from 'util';

async function getChild(parent){
  const readDir = util.promisify(fs.readdir);

  const dirList = await readDir(parent);

  return dirList.map(async (name) => {
    const dir = path.join(parent, name);
    const isDir = fs.lstatSync(dir).isDirectory();
    
    if (isDir) {
      return {
        type: 'directory',
        name,
        child: getChild(dir),
      }
    } else 
      return {
        type: 'file',
        name,
        child: null,
      }
  });
}

export async function cli(args) {
  let directoryTreeView = {};
  const folderPath = path.resolve('');
  directoryTreeView = Object.assign({}, directoryTreeView, {
    type: 'directory',
    name: 'root',
    folderPath,
    childs: await getChild(folderPath)
  });
}

我得到的结果

{ type: 'directory',
  name: 'root',
  folderPath: 'O:\\rootFolder',
  childs:
   [ Promise { [Object] },
     Promise { [Object] },
   ] 
}

必须是

{
  type: 'directory',
  name: 'root',
  child: [
    {
      type: 'directory',
      name: 'assets',
      child: [
        {
          type: 'file',
          name: 'icon1.png'
        },
      ]
    },
    {
      type: 'file',
      name: 'icon2.png',
      child: null,
    }
  ]
}

共1个答案

匿名用户

还可以尝试在初始化DirectoryTreeView之后调用异步函数。

export async function cli(args) {
    let directoryTreeView = {};
    const folderPath = path.resolve('');
    directoryTreeView = Object.assign({}, directoryTreeView, {
      type: 'directory',
      name: 'root',
      folderPath,
      childs: []
    });
  
    await getChild(folderPath).then(data => {
      data.forEach(path => {
        directoryTreeView.childs.push(path);
      }  
    )});
  }