Javascript parsing using NodeJS - node.js

Is there any module to parse javascript using node.js . I mean we are able to add and remove html content dynamically using cheerio nodejs module.
Similarly, we want to add, remove and manipulate a javascript method/variable. Is there any module to do that. I searched but unable to get one.
Thanks in Advance !!!

I would recommend the recast module. Install it via npm install --save recast. Below is a sample program that will read in the source of a module named user.js in the current directory. It will parse the source into an AST then from the AST re-generate the original source. Modify the AST with help from estraverse before you call recast.print(ast).code.
The source (does not incorporate estraverse -- exercise for the reader):
'use strict';
var recast = require('recast');
var path = require('path');
var fs = require('fs');
var file = path.resolve(__dirname, 'user.js');
var code = fs.readFileSync(file).toString();
var ast = recast.parse(code);
var output = recast.print(ast).code;
console.log(output);

Related

Defining modules in one file and requiring it in Node.js

I'm updating my code to include new packages so often and I have more than 100 files.
I want to make something like this,
File : dependencies.js :
const snekfetch = require("snekfetch");
const fs = require("fs");
It's very annoying to modify every file to add just a single package.
I'm trying to require the dependencies.js using this:
require("./dependencies.js")
But I see this in my console:
ReferenceError: snekfetch is not defined
Is there any way I can succeed?
I think you are not exporting the modules in dependencies.js
dependencies.js should look like,
const snekfetch = require("snekfetch");
const fs = require("fs");
module.exports = {
"snekfetch": snekfetch,
"fs": fs
};
Then you should be able to import this file and use it like as follows,
var dependencies = require('./dependencies.js');
// dependencies.fs.readFile();
Although there are much better ways to handle your imports then just creating a simple file of dependencies. Have a look at this link.

Error: Cannot find module 'togeojson'

I am attempting to use this module in node.js and am running into an "Error: Cannot find module 'togeojson'" error when I attempt to use the documented example code:
// using togeojson in nodejs
var tj = require('togeojson'),
fs = require('fs'),
// node doesn't have xml parsing or a dom. use xmldom
DOMParser = require('xmldom').DOMParser;
var kml = new DOMParser().parseFromString(fs.readFileSync('foo.kml', 'utf8'));
var converted = tj.kml(kml);
var convertedWithStyles = tj.kml(kml, { styles: true });
I ran npm init in the same directory that my app.js file (where the above code resides) is stored and I used the --save flag when installing the #mapbox/togeojson package to my application.
I am running node version 8.11.2 and npm v 6.1.0.
How do I go about debugging an issue like this in node/npm?
It is #mapbox/togeojson package, not togeojson, so it should be required like:
var tj = require('#mapbox/togeojson');

How does this npm build work?

https://github.com/apigee-127/swagger-converter
I see this code:
var convert = require('swagger-converter');
var fs = require('fs');
var resourceListing = JSON.parse(fs.readFileSync('/path/to/petstore/index.json').toString());
var apiDeclarations = [ JSON.parse(fs.readFileSync('/path/to/petstore/pet.json').toString()),
JSON.parse(fs.readFileSync('/path/to/petstore/user.json').toString()),
JSON.parse(fs.readFileSync('/path/to/petstore/store.json').toString())
];
var swagger2Document = convert(resourceListing, apiDeclarations);
console.log(JSON.stringify(swagger2Document, null, 2));
I'm confsued as to what exactly I'm supposed to do here to run this? Do I start a node http server?
To run the file you pasted, just save the code into a file like script.js. Then from the command line (with node installed) run node script.js. That will run the file. Here's a breakdown of what it's doing:
var convert = require('swagger-converter');
This line gets reference to the swagger-converter module that you linked to. That module is designed to allow you to convert swagger documents into JSON.
var fs = require('fs');
This line gets reference to the node built-in filesystem module (fs for short). It provides an API for interacting with the filesystem on your machine when the script is running.
var resourceListing = JSON.parse(fs.readFileSync('/path/to/petstore/index.json').toString());
This line could be broken down to:
var indexContent = fs.readFileSync('/path/to/petstore/index.json');
JSON.parse(indexContent.toString());
readFileSync returns the contents of the index.json file as a buffer object, which is easily turned into a simple string with the call to .toString(). Then they pass it to JSON.parse which parses the string and turns it into a simple JavaScript object.
Fun Fact: They could have skipped those steps with a simple var resourceListing = require('/path/to/petstore/index.json');. Node knows how to read JSON files and automatically turn them into JavaScript objects. You need only pass the path to require.
var apiDeclarations = [ JSON.parse(fs.readFileSync('/path/to/petstore/pet.json').toString()),
JSON.parse(fs.readFileSync('/path/to/petstore/user.json').toString()),
JSON.parse(fs.readFileSync('/path/to/petstore/store.json').toString())
];
This bit of code does the same thing as the resourceListing except it creates an array of three JavaScript objects based on those JSON files. They also could have used require here to save a bit of work.
Then finally they use the converter to do the conversion and then they log that data to the terminal where your script is running.
var swagger2Document = convert(resourceListing, apiDeclarations);
console.log(JSON.stringify(swagger2Document, null, 2));
JSON.stringify is the opposite of JSON.parse. stringify turns a JavaScript object into a JSON string whereas parse turns a JSON string into a JavaScript object.

Using Yeoman programmatically inside nodejs project

I want to use an yeoman generator inside a NodeJS project
I installed yeoman-generatorand generator-git (the generator that I want use) as locally dependency, and, at this moment my code is like this:
var env = require('yeoman-generator')();
var path = require('path');
var gitGenerator = require('generator-git');
var workingDirectory = path.join(process.cwd(), 'install_here/');
generator = env.create(gitGenerator);
obviously the last line doesn't work and doesn't generate the scaffold.
The question: How to?
Importantly, I want to stay in local dependency level!
#simon-boudrias's solution does work, but after I changed the process.chdir(), this.templatePath() and this.destinationPath() returns same path.
I could have use this.sourcePath() to tweak the template path, but having to change this to each yeoman generator is not so useful. After digging to yo-cli, I found the following works without affecting the path.
var env = require('yeoman-environment').createEnv();
env.lookup(function() {
env.run('generator-name');
});
env.create() only instantiate a generator - it doesn't run it.
To run it, you could call generator.run(). But that's not ideal.
The best way IMO would be this way:
var path = require('path');
var env = require('yeoman-generator')();
var gitGenerator = require('generator-git');
// Optionnal: look every generator in your system. That'll allow composition if needed:
// env.lookup();
env.registerStub(gitGenerator, 'git:app');
env.run('git:app');
If necessary, make sure to process.chdir() in the right directory before launching your generator.
Relevant documentation on the Yeoman Environment class can be found here: http://yeoman.io/environment/Environment.html
Also see: http://yeoman.io/authoring/integrating-yeoman.html
The yeoman-test module is also very useful if you want to pass predefined answers to your prompts. This worked for me.
var yeomanTest = require('yeoman-test');
var answers = require('from/some/file.json');
var context = yeomanTest.run(path.resolve('path/to/generator'));
context.settings.tmpdir = false; // don't run in tempdir
context.withGenerators([
'paths/to/subgenerators',
'more/of/them'
])
.withOptions({ // execute with options
'skip-install': true,
'skip-sdk': true
})
.withPrompts(answers) // answer prompts
.on('end', function () {
// do some stuff here
});

How do I get the ‘program name’ (invocation location) in Node.js?

I want the equivalent of $PROGRAM_NAME in Ruby, or ARGV[0] in C-likes, for Node.js. When I have a Node script that looks something like this,
#!/usr/bin/env node
console.log(process.argv[0])
… I get “node” instead of the name of the file that code is saved in. How do I get around this?
You can either use this (if called from your main.js file):
var path = require('path');
var programName = path.basename(__filename);
Or this, anywhere:
var path = require('path');
var programName = path.basename(process.argv[1]);
Use __filename? It returns the currently executing script.
http://nodejs.org/docs/latest/api/globals.html#globals_filename
For working with command line option strings check out the optimist module by Substack. Optimist will make your life much easier.
var inspect = require('eyespect').inspector();
var optimist = require('optimist')
var path = require('path');
var argv = optimist.argv
inspect(argv, 'argv')
var programName = path.basename(__filename);
inspect(programName, 'programName')
To install the needed dependencies:
npm install -S eyespect optimist

Resources