esprima 获取异步函数与同步函数类型里的代码
以下是使用 Esprima 获取异步函数和同步函数的代码示例:
const esprima = require('esprima');
const code = `
async function asyncFunc() {
console.log('Async function');
}
function syncFunc() {
console.log('Sync function');
}
`;
const ast = esprima.parseScript(code);
// 获取异步函数
ast.body.forEach((node) => {
if (node.type === 'FunctionDeclaration' && node.async) {
console.log('异步函数名:', node.id.name);
console.log('异步函数代码:', code.slice(node.start, node.end));
}
});
// 获取同步函数
ast.body.forEach((node) => {
if (node.type === 'FunctionDeclaration' && !node.async) {
console.log('同步函数名:', node.id.name);
console.log('同步函数代码:', code.slice(node.start, node.end));
}
});
输出结果:
异步函数名: asyncFunc
异步函数代码: async function asyncFunc() {
console.log('Async function');
}
同步函数名: syncFunc
同步函数代码: function syncFunc() {
console.log('Sync function');
}
以上代码使用 Esprima 解析代码,然后遍历语法树(AST)中的每个节点,判断是否为函数声明,并根据 async 属性判断是异步函数还是同步函数,最后输出函数名和函数代码。
原文地址: https://www.cveoy.top/t/topic/9XD 著作权归作者所有。请勿转载和采集!