Huge News!Announcing our $40M Series B led by Abstract Ventures.Learn More
Socket
Sign inDemoInstall
Socket

to-ast

Package Overview
Dependencies
Maintainers
1
Versions
1
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

to-ast

Converts JavaScript objects to equivalent ASTs

  • 1.0.0
  • latest
  • Source
  • npm
  • Socket score

Version published
Weekly downloads
115K
decreased by-1.25%
Maintainers
1
Weekly downloads
 
Created
Source

to-ast

This module converts JavaScript objects to an equivalent abstract syntax tree representation, compatible with the Mozilla Parser API. You can use it to generate JavaScript source code from objects, using escodegen.

Usage

Install with npm:

npm install to-ast

Here's a simple example:


var toAST = require('to-ast');
var escodegen = require('escodegen');

// get an AST from a number...
toAST(2) //=> { type: 'Literal', value: 2 }

// or if you want a source string...
escodegen.generate(toAST(2)) //=> '2'

Supported types

  • undefined
  • null
  • number, string, and boolean literals
  • functions
  • Node buffers
  • arrays
  • String, Number, and Boolean object wrappers
  • typed arrays and array buffers
  • dates
  • errors
  • regular expressions
  • object literals

Custom types

Most built-in JavaScript types as supported out of the box, but if you want to override the behavior for your particular object, you can provide a toAST method on your object:

var toAST = require('to-ast');
var escodegen = require('escodegen');

function Person(name) {
  this.name = name;
}

Person.prototype.toAST = function() {
  return {
    type: 'NewExpression',
    callee: { type: 'Identifier', name: 'Person' },
    arguments: [{ type: 'Literal', value: this.name }]
  };
};

escodegen.generate(toAST(new Person('Devon'))) //=> "new Person('Devon')"

License

MIT

Keywords

FAQs

Package last updated on 02 Apr 2015

Did you know?

Socket

Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.

Install

Related posts

SocketSocket SOC 2 Logo

Product

  • Package Alerts
  • Integrations
  • Docs
  • Pricing
  • FAQ
  • Roadmap
  • Changelog

Packages

npm

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc