简体   繁体   English

将树数据结构保存到文本文件JavaScript

[英]Saving a tree data structure to a text file JavaScript

I want to save a tree structure to a text file, I then want to reconstruct the file by reading the text file. 我想将树形结构保存到文本文件,然后通过读取文本文件来重建文件。 It will be used for a file tree that should look something like this: 它将用于应如下所示的文件树:

rootnode
|-dir 1
| |-file 1
| |-file 2
|
|-dir 2
|
|-dir 3
  |-file 3.1
  |
  |-dir 3.1
    |-fileName

This is a traversal that I have: 这是我的遍历:

    Tree.prototype.traversalDF = function(callBack) {

        (function depth(currentNode) {
            for (var i=0, length = currentNode.children.length; i < length; i++) {
                depth(currentNode.children[i]);
            }
            callBack(currentNode);
        })(this._root);
    };

this is how it is called: 这就是所谓的:

tree.traversalDF(function(node){
    console.log(node.parent);
    fs.appendFile(path.join(__dirname, '/testTree.txt'), node+ '\n', 'utf8');
})   

this only saves this '[object, object]' the same number of times there are nodes. 这样只会将此“ [对象,对象]”保存相同的次数。 But I want the data to be saved. 但是我想保存数据。

This is the node and the tree properties: 这是节点和树的属性:

//Every Node will have these properties
function Node(data) {
    this.data = data;
    this.children = [];
};

function Tree(data) {
    //this creates an instance of a node with data passed
    var node = new Node(data);
    //allows access to the properties of node
    this._root = node;

};

This is the saved data How could it be reconstructed: 这是保存的数据,如何重建它:

 {"data":"2.2","children":[]} {"data":"2.1","children":[]} {"data":"2","children":[{"data":"2.1","children":[]},{"data":"2.2","children":[]}]} {"data":"lemons","children":[]} {"data":"4.1","children":[{"data":"lemons","children":[]}]} {"data":"lemons2","children":[]} {"data":"5.11","children":[{"data":"lemons2","children":[]}]} {"data":"4","children":[{"data":"4.1","children":[{"data":"lemons","children":[]}]},{"data":"5.11","children":[{"data":"lemons2","children":[]}]}]} {"data":"one","children":[{"data":"2","children":[{"data":"2.1","children":[]},{"data":"2.2","children":[]}]},{"data":"4","children":[{"data":"4.1","children":[{"data":"lemons","children":[]}]},{"data":"5.11","children":[{"data":"lemons2","children":[]}]}]}]} 

Use JSON.stringify(node) instead of just node in the traversalDF callback. 使用JSON.stringify(node)而不是traversalDF回调中的仅node You actually don't need to traverse it at all; 实际上,您根本不需要遍历它。 you should be able to just call JSON.stringify(obj) to serialize it. 您应该可以只调用JSON.stringify(obj)进行序列化。

To deserialize it, just use JSON.parse(/* string */) after reading it from the file. 要反序列化,只需在从文件中读取它之后使用JSON.parse(/* string */)

The tree created is the same as the one desired however the it stores all the data required here is the code: 创建的树与所需的树相同,但是它存储所需的所有数据,这是代码:

const fs = require('fs');
const path = require('path');



//Every Node will have these properties
function Node(data) {
    this.data = data;
    this.children = [];
};

function Tree(data) {
    //this creates an instance of a node with data passed
    var node = new Node(data);
    //allows access to the properties of node
    this._root = node;

};

//--------------------------graph traversal code--------------------------------//

Tree.prototype.traversalDF = function(callBack) {

    (function depth(currentNode) {
        for (var i=0, length = currentNode.children.length; i < length; i++) {
            depth(currentNode.children[i]);
        }
        callBack(currentNode);
    })(this._root);
};

Tree.prototype.traversalBF = function(node, pathPart) {
    //determines number of children of the given node

    var length = node.children.length;

    var i = 0;
    var found = false;
    //cycles through until there is a match
    while( found != true && i <= length){
        if(node.children[i] != null){
            if(node.children[i].data == pathPart){
                found = true;
                //when there is a match it returns the node

                return node.children[i];
            }
        } else if( i == length) {
            var nodeFile = new Node(pathPart);

            //adds the file name onto the the node
            node.children.push(nodeFile);
            //sets the node parent to the currentNode
        // nodeFile.parent = node;

            return nodeFile;
        }
        i++;
    }
}

Tree.prototype.add = function(path){
var pathSplit = path.split('/');
//gets the length of the path
var pathLength = pathSplit.length;
//this compares the path to the nodes/directories
let compare = (currentNode, n) => {

    if(n == pathLength -1){

        //create a new node with file name as data
        var nodeFile = new Node(pathSplit[n]);
        //adds the file name onto the the node
        currentNode.children.push(nodeFile);
    }else{
        var newNode = () => this.traversalBF(currentNode, pathSplit[n]);

        compare(newNode(), n+1);
    };

};
compare(this._root, 1);
};


var tree = new Tree('one');

tree.add('one/2/2.1');
tree.add('one/2/2.2');
tree.add('one/hi');
tree.add('one/4/4.1');


tree.add('one/4/4.1/lemons');
tree.add('one/4/5.11/lemons2');

    tree.traversalDF(function(node){
        console.log(node.data);
    });

    //writeFileSyn used instead on appendFile so it overwrites the data in the .txt
    //necessary to use 'writeFileSync' otherwise next line attempts to read an empty file
    fs.writeFileSync(path.join(__dirname, '/testTree.txt'), JSON.stringify(tree) + '\n', 'utf8');
    //reads data from txt file
    var treeRecon = JSON.parse(fs.readFileSync(path.join(__dirname, '/testTree.txt')));
    //creates a tree
    var Reconstructed = new Tree(treeRecon._root.data);
    console.log(Reconstructed);

    for (i = 0; i < treeRecon._root.children.length; i++) {
        //for each child in the root in the children of the root.
        //the children are pushed onto the roots children hence recreating it.
        Reconstructed._root.children.push(treeRecon._root.children[i]);
    }
    console.log(Reconstructed);

    Reconstructed.traversalDF(function(node){
        console.log(node.data);

    });

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM