How to trace javascript code execution on nodejs while keeping track of variables change?

Viewed 146

I want to store debugged javascript code as a Json file, the debugged json file should have the information about the lineNumber, code on that line and local variables value for each step of the code execution.

Let's consider a simple example, I have a js code:

const add = (a, b) => {
    return a + b;
}

console.log(add(5, 4))

After debugging this code I should get a json file somewhat similar to this:

[
    {
        "line_number": 1,
        "code_one_line": "const add = (a, b) => {",
        "variables": [
            {
                "variable_name": "add",
                "variable_value": "undefined"
            },
            {
                "variable_name": "a",
                "variable_value": "undefined"
            },
            {
                "variable_name": "b",
                "variable_value": "undefined"
            }
        ]
    },
    {
        "line_number": 5,
        "code_one_line": "console.log(add(5, 4))",
        "variables": [
            {
                "variable_name": "add",
                "variable_value": "(a, b) => { return a + b; }"
            }
        ]
    },
    {
        "line_number": 2,
        "code_one_line": "    return a + b;",
        "variables": [
            {
                "variable_name": "a",
                "variable_value": 5
            },
            {
                "variable_name": "b",
                "variable_value": 4
            }
        ]
    },
    {
        "line_number": 2,
        "code_one_line": "    return a + b;",
        "variables": [
            {
                "variable_name": "a",
                "variable_value": 5
            },
            {
                "variable_name": "b",
                "variable_value": 4
            },
            {
                "variable_name": "Return value",
                "variable_value": 9
            }
        ]
    },
    {
        "line_number": 5,
        "code_one_line": "console.log(add(5, 4))",
        "variables": [
            {
                "variable_name": "add",
                "variable_value": "(a, b) => { return a + b; }"
            }
        ]
    }
]

note: I created this above Json manually, following the Vscode debugger.

As you can see from the above example, I want to trace a javascript code step by step on nodejs and store the debugged values in json file.

While searching for this, I came across the njsTrace library, it is great but it works on functions call only. I want the whole step-by-step tracing of code.

Any help would be appreciated.

0 Answers
Related