Node's Commander can't prompt terminal - node.js

I'm using the popular Commander npm module in a command-line program i'm building. It works great except that all of the functions it provides that solicit user input -- aka, choose, prompt, and password -- fail to work.
As an example I'm using:
program
.command('test')
.action(function(param) {
program.prompt('Username: ', function(name){
console.log('hi %s', name);
});
program.prompt('Description:', function(desc){
console.log('description was "%s"', desc.trim());
});
}
);
This results in the following error (yet it is copy and pasted directly out of the documentation/examples):
TypeError: Object # has no method 'prompt'
at Command. (lib/tg.js:780:11)
at Command.listener (node_modules/commander/index.js:249:8)
at Command.emit (events.js:98:17)
at Command.parseArgs (/node_modules/commander/index.js:480:12)
at Command.parse (/node_modules/commander/index.js:372:21)
at Object. (/lib/tg.js:806:9)
at Module._compile (module.js:456:26)
at Object.Module._extensions..js (module.js:474:10)
at Module.load (module.js:356:32)
at Function.Module._load (module.js:312:12)

Try using the Node Prompt module. Install it from npm with this command:
npm install prompt --save
The docs can be found here: https://github.com/flatiron/prompt
Make sure you also require it in your code, usually at the top.
var prompt = require('prompt');
Remember, Node is non-blocking. Multiple prompts will attempt to get user input at the same time. To get around this, split your prompts up into functions and call the next prompt in the callback.
Example:
var first_prompt = function() {
var schema = {
// Read the docs on creating a prompt schema
};
prompt.start();
prompt.get(schema, function(err, result) {
// Do stuff with the input
// Call the next prompt
next_prompt();
});
};

Related

Nodejs - passing commander arguments to forever-monitor child process

I have this node cli script
#!/usr/bin/env node
const path = require('path');
const forever = require('forever-monitor');
const script = path.format({dir: __dirname, base: 'pager.js'});
const chalk = require('chalk');
const commander = require('commander');
commander.version('1.0.0')
.option('-m, --message', 'set awesome message')
.parse();
const args = commander.opts();
const header = `
+---------------------+
| Awesome v1.0 |
+---------------------+
`;
const child = new (forever.Monitor)(script, {
max: 2,
silent: false,
args: args
});
child.start();
child.on('start', (process) => {
console.log(chalk.magenta.bold(header));
});
child.on('restart', () => {
console.log(`Forever restarting script for ${child.times} time`);
});
child.on('exit:code', (code) => {
console.log(`Forever detected script exited with code ${code}`);
});
I want to integrate commander togive the user the ability to pass arguments that will be parsed and then passed to the child process that is running until terminal is closed with the help of forever-monitor npm package. At the moment I've tried to use commander inside the child process but without success, it will be ignored. I've then moved it inside my index.js code but I don't know how to pass the arguments to the child process. At the moment I get this error if I pass the parsed arguments to the args option of forever monitor
host:awesome dev$ node . -m 'Hello!'
/Users/dev/Desktop/awesome/node_modules/forever-monitor/lib/forever-monitor/monitor.js:130
this.args.unshift(script);
^
TypeError: this.args.unshift is not a function
at new exports.Monitor (/Users/dev/Desktop/awesome/node_modules/forever-monitor/lib/forever-monitor/monitor.js:130:15)
at Object.<anonymous> (/Users/dev/Desktop/awesome/index.js:20:15)
at Module._compile (node:internal/modules/cjs/loader:1108:14)
at Object.Module._extensions..js (node:internal/modules/cjs/loader:1137:10)
at Module.load (node:internal/modules/cjs/loader:973:32)
at Function.Module._load (node:internal/modules/cjs/loader:813:14)
at Function.executeUserEntryPoint [as runMain] (node:internal/modules/run_main:76:12)
at node:internal/main/run_main_module:17:47
Can anyone give me some help about?
forever-monitor: the args configuration option passed to forever-monitor expects an array.
'args': ['foo','bar']
Commander: program.opts() returns a regular javascript object which is a hash with the keys being the option names. program.args is an array of the parsed command-arguments with recognised options and option-values removed.
In Commander, also have a look at .allowUnknownOption() and passThroughOptions() so Commander allows unrecognised options on the command line. The default behaviour is to show an error for unrecognised options.

Angular giving Syntax Error during initial configuration

I am trying to create an Angular application on a Windows 10 OS. Previously when I attempted to install Node.js and NPM I was getting 'Cannot find 'resolve' of undefined'. I solved it by downgrading my Node.js to 6.17 and the NPM to 3.10. I can now download the Angular CLI but when I use the 'new' command, I get the following error.
C:\Users\user_name\AppData\Roaming\npm\node_modules\#angular\cli\bin\ng:23
);
^
SyntaxError: Unexpected token )
at createScript (vm.js:56:10)
at Object.runInThisContext (vm.js:97:10)
at Module._compile (module.js:549:28)
at Object.Module._extensions..js (module.js:586:10)
at Module.load (module.js:494:32)
at tryModuleLoad (module.js:453:12)
at Function.Module._load (module.js:445:3)
at Module.runMain (module.js:611:10)
at run (bootstrap_node.js:394:7)
at startup (bootstrap_node.js:160:9)
When I open the file location I get the following:
#!/usr/bin/env node
'use strict';
// Provide a title to the process in `ps`.
// Due to an obscure Mac bug, do not start this title with any symbol.
try {
process.title = 'ng ' + Array.from(process.argv).slice(2).join(' ');
} catch (_) {
// If an error happened above, use the most basic title.
process.title = 'ng';
}
// This node version check ensures that extremely old versions of node are not used.
// These may not support ES2015 features such as const/let/async/await/etc.
// These would then crash with a hard to diagnose error message.
// tslint:disable-next-line: no-var-keyword
var version = process.versions.node.split('.').map(part => Number(part));
if (version[0] < 10 || version[0] === 11 || (version[0] === 10 && version[1] < 13)) {
process.stderr.write(
'Node.js version ' + process.version + ' detected.\n' +
'The Angular CLI requires a minimum Node.js version of either v10.13 or v12.0.\n\n' +
'Please update your Node.js version or visit https://nodejs.org/ for additional instructions.\n',
);
process.exit(3);
}
require('../lib/init');
It's complaining about the parentheses for the if statement. I tried getting rid of the parentheses and it only makes the situation worse. What would be the best way to go about solving this situation. WOuld it be better to use somehow install a new version of Node and work around the 'resolve' error or take with what I have with the version at hand?

Download plotly open source on node js

Can you download the entire module of plotly using node js. Right now, I am streaming data with plotly using node js by using my API keys. If there is a way, can yo give step by step instructions? I tried https://www.npmjs.com/package/plotly.js, but it does not work.
var plotly = require('plotly.js');
var initdata = [{x:[], y:[], stream:{token:'t2166m92ft', maxpoints:50}}];
var initlayout = {fileopt : 'overwrite', filename : 'nodenodenode5'};
plotly.plot(initdata, initlayout, function (err, msg) {
if (err) return console.log(err);
console.log(msg);
var stream1 = plotly.stream('t2166m92ft', function (err, res) {
if (err) return console.log(err);
console.log(res);
clearInterval(loop); // once stream is closed, stop writing
});
var i = 0;
var loop = setInterval(function () {
client.once('message', function (message) {
var data = { x : i , y : message.toString()};
var streamObject = JSON.stringify(data);
stream1.write(streamObject+'\n');
i++;
});
}, 5000);
});
}
when i tried install using npm install plotly.js, and ran my program I got :
\Users\intern\Documents\universal-ground-system\Node js\node_modules\plotly.js
rc\lib\index.js:397
var style = document.createElement('style');
^
ReferenceError: document is not defined
at Object.lib.addStyleRule (C:\Users\intern\Documents\universal-ground-syste
Node js\node_modules\plotly.js\src\lib\index.js:397:21)
at Object.<anonymous> (C:\Users\intern\Documents\universal-ground-system\Nod
js\node_modules\plotly.js\build\plotcss.js:61:16)
at Module._compile (module.js:409:26)
at Object.Module._extensions..js (module.js:416:10)
at Module.load (module.js:343:32)
at Function.Module._load (module.js:300:12)
at Module.require (module.js:353:17)
at require (internal/module.js:12:17)
at Object.<anonymous> (C:\Users\intern\Documents\universal-ground-system\Nod
js\node_modules\plotly.js\src\plotly.js:30:1)
at Module._compile (module.js:409:26)
Plotly open source library can not be used in node js. But can be used on client side javascript.
I got past this to some degree, but ran into another error, so close now it seems.
When I make a dom with jsdom it doesn't like to see window for some sort of async issue probably.
If you go into REPL load the file or otherwise get to make the new jsdom object, then you can do this sort of thing in REPL that references window and the needed document.
let jsdom = lib.require('jsdom');
//let window = (new jsdom.JSDOM('<p>Hello</p>')).window;
let dom = new jsdom.JSDOM('<p>Hello</p>');
/* While just testing I do this in REPL after .load index.js
let window = dom.window;
let document = window.document;
*/
So then I get a new error after npm install canvas that needs
apt-get install libcairo2-dev libjpeg8-dev libpango1.0-dev libgif-dev build-essential g++
first to properly build it on Ubuntu 16
so the new error is...
> let window = dom.window;
undefined
> let document = window.document;
undefined
>
>
> let plt = lib.require('plotly.js');
ReferenceError: self is not defined
at Object.254 (./node_modules/mapbox-gl/dist/mapbox-gl.js:509:29)
at s (./node_modules/mapbox-gl/dist/mapbox-gl.js:1:684)
at ./node_modules/mapbox-gl/dist/mapbox-gl.js:1:735
at Object.252../window (./node_modules/mapbox-gl/dist/mapbox-gl.js:505:25)
at s (./node_modules/mapbox-gl/dist/mapbox-gl.js:1:684)
at ./node_modules/mapbox-gl/dist/mapbox-gl.js:1:735
at Object.73.../package.json (./node_modules/mapbox-gl/dist/mapbox-gl.js:146:75)
at s (./node_modules/mapbox-gl/dist/mapbox-gl.js:1:684)
at e (./node_modules/mapbox-gl/dist/mapbox-gl.js:1:855)
>
I tried setting 'self' to 'document' and 'this' and get another error.
> self = document;
Document { location: [Getter/Setter] }
> plt = lib.plt = lib.require('plotly.js');
TypeError: Cannot read property 'hardwareConcurrency' of undefined
at Object.252../window (./node_modules/mapbox-gl/dist/mapbox-gl.js:505:834)
at s (./node_modules/mapbox-gl/dist/mapbox-gl.js:1:684)
at ./node_modules/mapbox-gl/dist/mapbox-gl.js:1:735
at Object.73.../package.json (./node_modules/mapbox-gl/dist/mapbox-gl.js:146:75)
at s (./node_modules/mapbox-gl/dist/mapbox-gl.js:1:684)
at e (./node_modules/mapbox-gl/dist/mapbox-gl.js:1:855)
at ./node_modules/mapbox-gl/dist/mapbox-gl.js:1:873
at ./node_modules/mapbox-gl/dist/mapbox-gl.js:1:150
Next I attempted to get window.navigator into self but that's apparently got nothing to do with the error. Somewhere else in mapbox-gl.js is glitching out.
I've only found a reference to harwareConcurrency in mapboxgl.js here
https://github.com/mapbox/mapbox-gl-js/issues/899
Seems misleading to say it's a nodejs library when it only works in the browser? https://plot.ly/nodejs/
Just now I'm seeing something about an API Key? I guess I'm barking down the wrong tree sideways. Big mistake here.

mongodb with nodejs

this is th code I am using inserting a document to mongodb.
var client = new Db('test', new Server("127.0.0.1", 27017, {}), {w: 1}),
test = function (err, collection) {
collection.insert({a:2}, function(err, docs) {
collection.count(function(err, count) {
test.assertEquals(1, count);
});
// Locate all the entries using find
collection.find().toArray(function(err, results) {
test.assertEquals(1, results.length);
test.assertTrue(results[0].a === 2);
// Let's close the db
client.close();
});
});
};
client.open(function(err, p_client) {
client.collection('test_insert', test);
});
but while running I am getting error
xports, require, module, __filename, __dirname) { var client = new Db('test',
^
ReferenceError: Db is not defined
at Object. (C:\Users\Basic node\cheerio\mongonode.js:1:81
at Module._compile (module.js:449:26)
at Object.Module._extensions..js (module.js:467:10)
at Module.load (module.js:356:32)
at Function.Module._load (module.js:312:12)
at Module.runMain (module.js:492:10)
at process.startup.processNextTick.process._tickCallback (node.js:244:9)
can you suggest me how to solve this problem
thanks in advance
Please import all the required modules, which you are using. Db is not defined points out that Db is defined in some other module or you have forgot to declare it.
You'll notice this exact code block posted in a number of different stackoverflow questions. The problem here is that this is a copy and pasted code block from mongodb's documentation, as is in fact the first example of a mongodb nodejs program.
https://npmjs.org/package/mongodb
You'll find this under "Introduction" as "A simple example of inserting a document."
It's clearly an incomplete example, but a lot of people are just trying it out to see if they've got everything installed correctly and immediately run into a wall.
Most people will have installed the mongodb driver, but will be missing something at the top like this:
var mongodb = require('mongodb');
var Db = mongodb.Db;
var Server = mongodb.Server;
I also fell into the copy-paste trap here and ran into another issue with the "assertEquals" method not existing. I've seen other people reference that function in other places on the web, but not really sure how it works.
In any case, to make it work for me, I required the assert module:
var assert = require('assert');
And then I replaced the assertEquals lines with something like this:
assert.equal(1, count, "Unexpected result");
Note that you're going to run into an issue if you've run this a couple of times; it's going to count the number of things in that table, and there is going to be more than one.
You'll have to figure out how to get into mongo's CLI and remove them to get it to run successfully.
Try to install mongodb native driver
npm install mongodb

Creating temporary view in couchdb using node-couchdb-api

I am trying to connect couchdb using node-couchdb-api at nodejs level as mentioned in the following link http://dominicbarnes.us/node-couchdb-api/.My couchdb version is 1.1.1 and nodejs version is 0.6.10.
For creating temporary view as mentioned in api http://dominicbarnes.us/node-couchdb-api/api/database/tempView.html I have written the following code.
var couchdb = require("couchdb-api");
var server = couchdb.srv(localhost, 5984, false, false);
var db = server.db("test");
var map = function (doc) {
emit(null, 1);
};
var reduce = "_sum";
var query = { include_docs: true };
db.tempView(map, reduce, query, function (err, response) {
console.log(response);
});
But i am facing the following problem.
C:\Program Files\nodejs\node_modules\couchdb-api>node server.js
node.js:201
throw e; // process.nextTick error, or 'error' event on first tick
^
TypeError: Cannot read property '0' of null
at C:\Program Files\nodejs\node_modules\couchdb-api\lib\util.js:24:39
at Array.map (native)
at Object.formatFunction (C:\Program Files\nodejs\node_modules\couchdb-api\lib\util.js:22:25)
at Object.tempView (C:\Program Files\nodejs\node_modules\couchdb-api\lib\database.js:285:28)
at Object.<anonymous> (C:\Program Files\nodejs\node_modules\couchdb-api\server.js:27:4)
at Module._compile (module.js:441:26)
at Object..js (module.js:459:10)
at Module.load (module.js:348:31)
at Function._load (module.js:308:12)
at Array.0 (module.js:479:10)
please suggest me to resolve the issue.
Thanks in advance.
sorry about the problem you were experiencing. I'm the creator of that module, and I've just pushed version 1.1.2 up to NPM which addresses your problem. (and includes a unit test to make sure it doesn't happen again)
Just update to the latest version via npm update couchdb-api and you should be set to go. Let me know if you have further issues.

Resources