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

时间:2018-01-15 19:10:47

标签: javascript tree text-files

我想将树结构保存到文本文件中,然后我想通过读取文本文件来重建文件。 它将用于一个看起来像这样的文件树:

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

这是我的遍历:

    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.traversalDF(function(node){
    console.log(node.parent);
    fs.appendFile(path.join(__dirname, '/testTree.txt'), node+ '\n', 'utf8');
})   

这只会保存这个[对象,对象]&#39;节点数相同的次数。但我希望保存数据。

这是节点和树属性:

//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;

};

这是保存的数据如何重建:

&#13;
&#13;
{"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":[]}]}]}]}
&#13;
&#13;
&#13;

2 个答案:

答案 0 :(得分:1)

JSON.stringify(node)回调中使用node而非traversalDF。你实际上根本不需要遍历它;您应该可以致电JSON.stringify(obj)来序列化它。

要反序列化,只需在从文件中读取后使用JSON.parse(/* string */)

答案 1 :(得分:0)

创建的树与所需的树相同,但是它存储的所有数据都是代码:

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);

    });