Search code examples
node.jstraversal

nodejs Traverse (js-traverse) module: How to 'break' traversing


How to break/stop traversal in nodejs traverse module?

I am traversing a json and on certain condition, I want to stop traversing.

traverse(req.body).forEach(function (xnode) { log.info("Inspecting node: "+xnode); ... ... //If JSON Threat is detected, return error if(Object.keys(err).length > 0){ return next(new Error(JSON.stringify(err))); //traversing should halt here but it continues //DO I need to explicitly break it? } });

During debugging, I observed the return statement sends control to calling (connect) middleware but traverse continues in background. I didn't find any break/stop options in docs. How to stop traversing after the error occures?

Thanks in advance for your input.


Solution

  • Turns out there is this.stop() method in traverse module to stop traversing the object. Although this method is not mentioned in module documentation.

    traverse(obj).forEach(function (x) {
        console.log("key: "+this.key+"\tValue: "+x+"\tLevel: "+this.level);
        if(this.key==='b'){
            console.log("Halting Traversal: "+this.key+" value: "+x);
            this.stop();
        }
     }