How do I get the ‘program name’ (invocation location) in Node.js? - 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

Related

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');

node_modules path programmatically

I am using protractor and I want to get programmatically the npm node_modules path from the global system.
For example my selenium jar is installed here:
C:/Users/myuser/AppData/Roaming/npm/node_modules/protractor/node_modules/webdriver-manager/selenium/selenium-server-standalone-3.7.1.jar
and I wanted to get
C:/Users/myuser/AppData/Roaming/npm/node_modules/
or
C:/Users/myuser/AppData/Roaming/npm/node_modules/protractor/node_modules/
I wrote this small script, which will look for my jar in the paths
var path = require('path');
var fs = require('fs');
var paths = path.getModulePaths()
for (i=0;i<paths.length;i++) {
file = path.join(paths[i],'webdriver-manager','selenium','selenium-server-standalone-3.7.1.jar')
if (fs.existsSync(file)) {
var seleniumServerJar = file
continue
}
}
here I supposed that this function is available
var paths = path.getModulePaths()
but it's not. I used to write an equivalent in Python, which is:
import sys
print sys.path
I guess you are expecting to start a webdriver manager programatically. Try below code:
var pkgPath = require.resolve('protractor');
var protractorDir = path.resolve(path.join(path.dirname(pkgPath), '..', 'bin'));
var webdriverManagerPath = path.join(protractorDir, '/' + 'webdriver-manager'));

Javascript parsing using NodeJS

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);

node child_process.spawn not working with spaces in path on windows

How to provide a path to child_process.spawn
For example the path:
c:\users\marco\my documents\project\someexecutable
The path is provided by the enduser from a configuration file.
var child_process = require('child_process');
var path = require('path');
var pathToExecute = path.join(options.toolsPath, 'mspec.exe');
child_process.spawn(pathToExecute, options.args);
Currently only the part after the space is used by child_process.spawn
I also tried by adding quotes arround the path like this:
var child_process = require('child_process');
var path = require('path');
var pathToExecute = path.join(options.toolsPath, 'mspec.exe');
child_process.spawn('"' + pathToExecute + '"', options.args);
However this results in a ENOENT error.
The first parameter must be the command name, not the full path to the executable. There's an option called cwd to specify the working directory of the process, also you can make sure the executable is reachable adding it to your PATH variable (probably easier to do).
Also, the args array passed to spawn shouldn't contain empty elements.
You code should look something like this:
child_process.spawn('mspec.exe', options.args, {cwd: '...'});
As per https://github.com/nodejs/node/issues/7367#issuecomment-229728704 one can use the { shell: true } option.
For example
const { spawn } = require('child_process');
const ls = spawn(process.env.comspec, ['/c', 'dir /b "C:\\users\\Trevor\\Documents\\Adobe Scripts"'], { shell: true });
Will work.
I am using spawn frequently, the way I solved the problem is to use process.chdir. So if your path is c:\users\marco\my documents\project\someexecutable then you should do the following:
process.chdir('C:\\users\\marco\\my documents\\project');
child_process.spawn('./myBigFile.exe', options.args);
Note the double \s, that's how it worked for me.

Meteor project path from a smartpackage

I was looking for a way to look up the meteor project path from a smart package (e.g.: obtain the path of the directory where the .meteor folder is ...).
I was not able to do it using node's __dirname and __filename because somehow in meteor they are not avaiable.
Any tips ?
As of Meteor 0.6.0 this would be:
var path = Npm.require('path');
var basepath = path.resolve('.');
From a smartpackage (0.6.5+):
var path = Npm.require('path');
var base = path.resolve('.');
base in this case gets you the position of your package ..
/User/username/projects/project/.meteor/local/programm/server/...
.. might even be deeper
but we want
/User/username/projects/project/
.. so split at .meteor
base = base.split('.meteor')[0];
Or as two-liner
var path = Npm.require('path');
var base = path.resolve('.').split('.meteor')[0];;
This works for me in Meteor 0.5.0:
var require = __meteor_bootstrap__.require;
var path = require('path');
var basepath = (path.resolve('.'));
You can actually get access to node:
var __dirname = __meteor_bootstrap__.__dirname;
You could try (only on server side)
process.env.PWD which returns something like that for me (OSX):
'/Users/myusername/Desktop/myproject'
With that command you get the root of meteor project.

Resources