Refactor the handleNode method and improve caching.