【问题标题】:How to store filesystem information in Typescript?如何在 Typescript 中存储文件系统信息?
【发布时间】:2021-04-19 13:31:05
【问题描述】:

我需要创建一个虚拟文件系统。 基本上我想给用户一个输入来创建/修改/删除具有他们将提供的属性的文件 - 文件名、大小、文件夹名。 文件存储在一个文件夹中。

所以基本上我想将上述信息存储在一个数组/或数据结构中,以便我可以检索回来并给出摘要 - XYZ 文件存放在 Folder7 中 DYT文件存放在文件夹8中

用户现在可以将 XYZ 文件移动到文件夹 8,也可以将其删除。这些不是真实文件,只是程序运行时创建的虚拟文件名/数据点。

此外,我想根据块输入期间的大小存储这些文件。例如- 如果我创建包含 100 个块和 1 个块 = 1mb 的数组。我创建了一个 3MB 的文件,这意味着它将消耗 3 个块,并且我可以检索到 a[0]、a[1]、a[2] 具有文件 xyz 的信息。

基本上我正在创建一个文件系统。

存储此信息然后轻松检索以进行摘要的最佳方式是什么。

我想在打字稿中完成所有这些工作。我不想使用任何文件系统 API。我需要建立一个虚拟模型。

【问题讨论】:

    标签: javascript arrays typescript multidimensional-array filesystems


    【解决方案1】:

    这样的?我还没试过。

    const BLOCK_SIZE = 1e6;
    
    interface VNode {
        name: string;
        parent: VFolder;
    }
    
    class VFile implements VNode {
        name: string;
        parent: VFolder;
        private _data: Buffer[];
    
        constructor(name: string, data: Buffer = Buffer.alloc(0)) {
            this.name = name;
    
            this._data = new Array(Math.ceil(data.byteLength/BLOCK_SIZE));
            for (let i = 0; i < data.byteLength; i+=BLOCK_SIZE) {
                this._data.push(data.slice(i, i+BLOCK_SIZE));
            }
        }
    
        get size() {
            return (this._data.length-1)*BLOCK_SIZE + (this._data.length === 0 ? 0 : this._data[this._data.length-1].byteLength);
        }
    
        delete() {
            this._data = [];
            if (this.parent === null) return true;
            return this.parent.removeChild(this);
        }
    
    }
    
    class VFolder implements VNode {
        name: string;
        parent: VFolder;
        private _childs: VNode[];
    
        constructor(name: string) {
            this.name = name;
        }
    
        addChild(node: VNode) {
            node.parent = this;
            this._childs.push(node);
        }
    
        removeChild(node: VNode) {
            const index = this._childs.indexOf(node);
            if (index === -1) return false;
            this._childs.splice(index, 1)[0].parent = null;
            return true;
        }
    
    }
    
    const root = new VFolder("/");
    root.addChild(new VFile("testfile123.txt", Buffer.from("mystring datatatat", "utf-8")));
    

    以后还需要一些函数来读取或修改数据...

    【讨论】:

    • Parent 语句中的代码有错误 - VFolder
    猜你喜欢
    • 2016-03-15
    • 1970-01-01
    • 2010-09-08
    • 2021-06-25
    • 1970-01-01
    • 2010-09-16
    • 1970-01-01
    • 1970-01-01
    • 2019-11-23
    相关资源
    最近更新 更多