From e6a72aae2731e0beb4f368c52e31aa0df0d2a4ea Mon Sep 17 00:00:00 2001 From: aiyingfeng Date: Mon, 17 Jul 2023 20:51:53 +0800 Subject: [PATCH] =?UTF-8?q?AST=E6=93=8D=E4=BD=9C=E4=B9=8BAPI=E7=94=A8?= =?UTF-8?q?=E6=B3=95-path=E8=B7=AF=E5=BE=84?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../5.AST操作之API用法-path路径/README.md | 39 +++++++++++++++++++ .../decode_obfuscator.js | 4 +- 2 files changed, 41 insertions(+), 2 deletions(-) diff --git a/AST抽象语法树/5.AST操作之API用法-path路径/README.md b/AST抽象语法树/5.AST操作之API用法-path路径/README.md index 704a01b..0428db1 100644 --- a/AST抽象语法树/5.AST操作之API用法-path路径/README.md +++ b/AST抽象语法树/5.AST操作之API用法-path路径/README.md @@ -227,3 +227,42 @@ var a; ``` **替换path,单路径可以使用`replaceWith`方法,多路径则使用`replaceWithMultiple`方法** + +需求:把var a = 123; 修改成var a = 3 ,用replaceWith方法 + +```javascript +const fs = require('fs'); +const {parse} = require("@babel/parser"); +const traverse = require("@babel/traverse").default; +const generator = require("@babel/generator").default; +let encode_file = "./encode.js"; + +let js_code = fs.readFileSync(encode_file, {encoding: "utf-8"}); +let ast = parse(js_code, { + sourceType: 'module', +}); + +const visitor = { + enter(path) { + if (path.isNumericLiteral() && path.node.value == 123) { + path.replaceWith({type: "NumericLiteral", value: 3}); + } + }, +} + +traverse(ast, visitor); + +// 写入文件 +let {code} = generator(ast); +console.log(code) +fs.writeFile('decode.js', code, (err) => { +}); +``` + +打印内容: + +```javascript +var a = 3; +``` + +注意点,必须加上`&& path.node.value == 123`判断,否则就是无限循环 \ No newline at end of file diff --git a/AST抽象语法树/5.AST操作之API用法-path路径/decode_obfuscator.js b/AST抽象语法树/5.AST操作之API用法-path路径/decode_obfuscator.js index 08e1824..f9f890e 100644 --- a/AST抽象语法树/5.AST操作之API用法-path路径/decode_obfuscator.js +++ b/AST抽象语法树/5.AST操作之API用法-path路径/decode_obfuscator.js @@ -11,8 +11,8 @@ let ast = parse(js_code, { const visitor = { enter(path) { - if (path.isNumericLiteral()) { - path.replaceWith({type:"NumericLiteral",value:3}); + if (path.isNumericLiteral() && path.node.value == 123) { + path.replaceWith({type: "NumericLiteral", value: 3}); } }, }