npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2026 – Pkg Stats / Ryan Hefner

@alu0101056944/espree-logging

v1.5.2

Published

Adds logs to javascript code

Readme

Open in Codespaces

Práctica Espree logging

API

Table of Contents

transpile

Parameters

  • inputFile string path to input file
  • outputFile string path to output file

addLogging

Parameters

Returns string logged code

addBeforeCode

Parameters

Ejecutable

El ejecutable bin/log.js puede ser utilizado de la siguiente forma:

Arguments:
  filename                 file with the original code

Options:
  -V, --version            output the version number
  -o, --output <filename>  file in which to write the output
  -h, --help               display help for command

Ejemplo de ejecución:

npx funlog test/data/test1.js -o output.txt

Instalación

Para instalar utilizar el siguiente comando:

npm i

Resumen de lo aprendido

Estructura de el arbol AST

Un nodo FunctionDeclaration tiene un una propiedad body, una propiedad params y una propiedad args y el body suele ser un BlockStatement cuyo body es un array. Dentro de ese array podemos meter otros nodos que queramos, capacidad que aplicamos para incluir un nodo CallStatement equivalente a console.log(...)

Indicar los valores de los argumentos

Se ha modificado el código de logging-espree.js para que el log también indique los valores de los argumentos que se pasaron a la función. Ejemplo:

function foo(a, b) {
  var x = 'blah';
  var y = (function (z) {
    return z+3;
  })(2);
}
foo(1, 'wut', 3);
function foo(a, b) {
    console.log(`Entering foo(${ a }, ${ b })`);
    var x = 'blah';
    var y = function (z) {
        console.log(`Entering <anonymous function>(${ z })`);
        return z + 3;
    }(2);
}
foo(1, 'wut', 3);

Para ello se modificó la función addBeforeCode() para que incluya un binding params en el string de salida del console.log(). Dicho binding es un array de elementos String construido a partir de la propiedad params del nodo FunctionDeclaration.

CLI con Commander.js

Se importa commander y se obtiene el objeto program del mismo. Se invoca sobre ese objeto la configuración que queremos que tenga el ejecutable CLI. Luego invocamos su método program.parse(process.argv) para que procese la entrada de CLI y haga lo que lo hemos configurado para hacer.

  • .option() para poder utilizar la opción -o
  • .argument() para tener un argumento obligatorio.
  • .version() recibe la versión del package.json
  • .action() recibe un callback que tendrá tantos parámetros como argumento, salvo el último, que es un objeto options con los valores de cada opción.

Reto 1: Soportar funciones flecha

Lo que hacemos es utilizar estraverse.traverse(ast, {enter:(node, parents) => {...}}) para recorrer el árbol de sintaxis abstracto (AST) nodo por nodo. Si se detecta que el corresponde a una declaración de función se le agrega una nueva sentencia a la misma. Es ahí donde entra addBeforeCode() para agregar dicho nodo.

    (...)
    estraverse.traverse(ast, {
        enter: function(node, parent) {
            if (/* si nodo declaración de función */) {
                addBeforeCode(node);
            }
        }
    });
    (...)

El problema está en que las funciones flecha son de tipo ArrowFunctionDeclaration, y ese nodo no está originalmente en la función, por lo que se le agrega.

Reto 2: Añadir el número de línea

Espree permite obtener un objeto loc que contiene como propiedades start y end, los cuales tienen a su vez la propiedad line y column. Basta con utilizar loc.start.line en la función addBeforeCode():

(...)
var beforeCode = "console.log(`Entering " + name + `(${params})` +
      ` at line ${node.loc.start.line}\`);`;
(...)

Tras haber activado el objeto en la configuración de espree.parse():

const ast = espree.parse(code, {ecmaVersion: 6, loc: true /* activamos el objeto loc */});

Tests and Covering

Test results with mocha

sucessful test

Code coverage using nyc

nyc result