UNPKG

@alu0101209067/addlogging

Version:
96 lines (72 loc) 2.61 kB
<!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <title>JSDoc: Source: my-sol-logging-espree.js</title> <script src="scripts/prettify/prettify.js"> </script> <script src="scripts/prettify/lang-css.js"> </script> <!--[if lt IE 9]> <script src="//html5shiv.googlecode.com/svn/trunk/html5.js"></script> <![endif]--> <link type="text/css" rel="stylesheet" href="styles/prettify-tomorrow.css"> <link type="text/css" rel="stylesheet" href="styles/jsdoc-default.css"> </head> <body> <div id="main"> <h1 class="page-title">Source: my-sol-logging-espree.js</h1> <section> <article> <pre class="prettyprint source linenums"><code>#!/usr/bin/env node const esprima = require('espree'); const estraverse = require('estraverse'); let escodegen = require('escodegen'); /** * Function that recive a code like a string and then create a code * @param {string} code * @returns {string} */ module.exports.addLogging = function(code, pattern = '') { let ast = esprima.parse(code, {ecmaVersion: 6, loc : true}); estraverse.traverse(ast, { enter: function(node, parent) { if (node.type === 'FunctionDeclaration' || node.type === 'FunctionExpression' || node.type === 'ArrowFunctionExpression') { if (!pattern || (node.id === null &amp;&amp; parent.id.name.match(pattern)) || node.id &amp;&amp; node.id.name.match(pattern)) { addBeforeCode(node); } } } }); return escodegen.generate(ast); } /** * Function that recive a node add one line of code before code * @param {} node * @returns {void} */ function addBeforeCode(node) { let name = node.id ? node.id.name : '&lt;anonymous function>'; const params = node.params.map(param =>`\$\{${param.name}\}`); let beforeCode = `console.log(\`Entering ${name}(${params}) at line ${node.loc.start.line}\`);`; let beforeNodes = esprima.parse(beforeCode, {ecmaVersion: 6}).body; // Is an Array of ASTs node.body.body = beforeNodes.concat(node.body.body); }</code></pre> </article> </section> </div> <nav> <h2><a href="index.html">Home</a></h2><h3>Global</h3><ul><li><a href="global.html#addBeforeCode">addBeforeCode</a></li><li><a href="global.html#addLogging">addLogging</a></li></ul> </nav> <br class="clear"> <footer> Documentation generated by <a href="https://github.com/jsdoc/jsdoc">JSDoc 3.6.6</a> on Tue Mar 09 2021 23:00:46 GMT+0000 (Coordinated Universal Time) </footer> <script> prettyPrint(); </script> <script src="scripts/linenumber.js"> </script> </body> </html>