vorpal .validate throwing error - node.js

I have a vorpal command that looks like this:
I am running version 1.9.5.
const vorpal = require('vorpal')()
vorpal
.command('temp [dev]')
.validate(function() {
return false
})
.action(function() {
...
})
vorpal.parse(process.argv)
And when i run pnt temp in my terminal I get this error thrown:
/Users/samm/Sites/pnt/node_modules/vorpal/dist/vorpal.js:169
throw new Error(err);
^
Error: null
at EventEmitter.<anonymous> (/Users/samm/Sites/pnt/node_modules/vorpal/dist/vorpal.js:169:17)
at callback (/Users/samm/Sites/pnt/node_modules/vorpal/dist/vorpal.js:830:22)
at /Users/samm/Sites/pnt/node_modules/vorpal/dist/vorpal.js:961:7
at EventEmitter._commandSetCallback (/Users/samm/Sites/pnt/node_modules/vorpal/dist/session.js:446:5)
at EventEmitter.session.completeCommand (/Users/samm/Sites/pnt/node_modules/vorpal/dist/session.js:526:12)
at onCompletion (/Users/samm/Sites/pnt/node_modules/vorpal/dist/session.js:456:10)
at EventEmitter.session.execCommandSet (/Users/samm/Sites/p nt/node_modules/vorpal/dist/session.js:471:5)
at EventEmitter.vorpal._exec (/Users/samm/Sites/pnt/node_modules/vorpal/dist/vorpal.js:960:18)
at EventEmitter.vorpal._execQueueItem (/Users/samm/Sites/pnt/node_modules/vorpal/dist/vorpal.js:751:17)
at EventEmitter.vorpal._queueHandler (/Users/samm/Sites/pnt/node_modules/vorpal/dist/vorpal.js:735:10)

I admit that this is looking ugly, and they will probably fix this in future versions, but this looks like the correct behaviour.
Returning false or a string from .validate should throw an error, as this means that you don't accept the arguments. If you return a string that string will be shown to the user (return "I don't want no scrubs.").
So from the code that you posted this is the correct behaviour.
If you like the errormessage from .validate to be different, I recommend you post an issue on vorpal's issue tracker. (Even though I can see you have already done that).

Related

NodeJS assert does not throw passed error

I have just started using NodeJS's assert Module, and, given that I have understood it correctly, I can pass a custom error instance that should be thrown instead of an AssertionError if the assertion fails.
I.e., the first line in the following code throws an AssertionError and the second line throws an Error:
const assert = require('assert');
assert(false);
assert(false, new Error('abc'));
However, on my system, this does not seem to work. I have the following code:
try {
assert(false, new Error('abc'));
} catch (error) {
console.log(error.constructor.name);
}
and the Output I get is 'AssertionError'. Interestingly, when I try to do the same thing using the REPL, the output is the expected 'Error'.
I use NodeJS v15.8.0 in an alpine Docker container.

TypeError: invNum.next is not a function

I have tried this code :
const invNum = require('invoice-number');
router.post('/checkout', async (req, res, next) => {
if (!req.session.cart) {
return res.redirect('/pos/');
}
var saleList = Sale.find().sort({ _id: -1 }).limit(1); // removed (err, data)=>{} to simply view it is working tested already
var settings = await Setting.find({}); // removed try and catch to simply view it is working tested already
var ticketNumber;
ticketNumber = !saleList ? invNum.next('0000000') : invNum.next(saleList.ticket_number);
var sale = new Sale({
ticket_number:ticketNumber,
cart: req.session.cart,
created_at: new Date()
});
sale.save((err, product) => {
createReceipt(settings, req.session.cart, "receipts/"+ticketNumber+".pdf");
req.session.cart = null;
res.redirect('/pos/');
});
});
I got this error:
TypeError: invNum.next is not a function
The problem is with invNum.next().
invNum.next() is a Node.js module to generate invoice number sequentially installed from npm.
Example:
invNum.next('2017/08/ABC001')
// => 2017/08/ABC002
I have tried already suggestions from previous stackoverflow posts by trying Promises or await async function in order to get this code to work. Hopefully, you can help or suggest something. Thank you.
There is a problem in version of invoice-number module. In the npm it is showing as 1.0.6 but in the GitHub repository it has 1.0.5 in the package.json file.
https://github.com/amindia/invoice-number.
I have tested this module by taking from Github repository and it's working fine.
Please take the source of this module from the given link it will works fine.
Seems to be some error in the module. I tried the below code snippet on RunKit
https://runkit.com/embed/ws2lv1y38mt4
var invNum = require('invoice-number')
try{
invNum.next('sdfsd1')
} catch(e){
console.log(e)
}
Getting the same error
I got this error:
TypeError: invNum.next is not a function UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch()
What is the output when you use the console.log on invNum?
Also use try catch and inside call invNum.next with await. Maybe something inside this function is throwing an error.
Edit: as jfriend00 says, if an plain text (like your "0000...") is working, probably the saleList is returning some error and you are not catching or treating the error.
Edit2: The last update on this NPM code is from 1 year ago and fewer people used this lib, probably is broken.
There is some part of the code from the index.js of the lib:
function _next (invoiceNumber) {
if (!invoiceNumber)
throw new Error('invoiceNumber cannot be empty')
var array = invoiceNumber.split(/[_/:\-;\\]+/)
var lastSegment = array.pop()
var priorSegment = invoiceNumber.substr(0, invoiceNumber.indexOf(lastSegment))
var nextNumber = alphaNumericIncrementer(lastSegment)
return priorSegment + nextNumber}
var api = { next: _next}
module.exports = api

Mocha assertion error: expected {} to be a string

I've been beating my head all morning on this and I'm pretty sure I'm just missing something simple. It appears I'm getting a new object ({}) for a return value when I'm expecting a string, but even if I hard code a string for a return value I get the same error.
I've worked through the examples found here with no trouble. My package.json is set to test properly (or at least I don't think that's the problem, but I can post it as well if it'll help troubleshoot my problem). I'm new-ish to Node.js (but well experienced with JS) & just learning Mocho & Chai.
What am I missing? Why am I getting what appears to be an empty object when I should be getting a string? What's causing the test to fail?
I've written a simple API to get the username from a host PC:
const username = require('username');
exports.getUserName = function() {
console.log(username.sync());
return username.sync();
};
And I've written a test using Mocha & Chai:
var expect = require("chai").expect;
var getUserName = require('./username.js');
describe("User name API", function () {
it("Returns a string with the user's name", function () {
expect(getUserName).to.be.a('string');
});
});
Here's the error that's returned when I run the test with npm test:
> sbserialwidget#0.0.1 test C:\deg\node_modules\sbSerialWidget
> mocha --reporter spec
running
User name API
1) Returns a string with the user's name
0 passing (13ms)
1 failing
1) User name API Returns a string with the user's name:
AssertionError: expected {} to be a string
at Context.<anonymous> (C:\deg\node_modules\sbSerialWidget\test\username.js:6:29)
at callFn (C:\deg\node_modules\sbSerialWidget\node_modules\mocha\lib\runnable.js:334:21)
at Test.Runnable.run (C:\deg\node_modules\sbSerialWidget\node_modules\mocha\lib\runnable.js:327:7)
at Runner.runTest (C:\deg\node_modules\sbSerialWidget\node_modules\mocha\lib\runner.js:429:10)
at C:\deg\node_modules\sbSerialWidget\node_modules\mocha\lib\runner.js:535:12
at next (C:\deg\node_modules\sbSerialWidget\node_modules\mocha\lib\runner.js:349:14)
at C:\deg\node_modules\sbSerialWidget\node_modules\mocha\lib\runner.js:359:7
at next (C:\deg\node_modules\sbSerialWidget\node_modules\mocha\lib\runner.js:285:14)
at Immediate._onImmediate (C:\deg\node_modules\sbSerialWidget\node_modules\mocha\lib\runner.js:327:5)
If I change the test to expect an object, the test works: expect(getUserName).to.be.an('object');.
However if I do a console.log(typeof username.sync()); it says it's a string.
What do I need to do to fix this?
Edit for solution:
Here's the code that I eventually got to work. I think part of the problem was a path issue (I'm in a Windows environment), partly me simply not quite understanding what needed to be done, and finally me not understanding how to call the function properly in the test (see below).
Here's the modified username.js code:
const username = require('username');
exports.getUserName = function() {
console.log(username.sync());
return username.sync();
}
Here's the modified usernametest.js:
var expect = require("chai").expect;
//here's where one point of confusion was, I was trying to call the original getUserName()
//function, but it's been turned into a variable called username
var username = require('..\\js\\username.js').getUserName;
describe("User name API", function () {
it("returns a string with the user's name", function () {
//so here, instead of calling username.getUserName(), I call username()
//instead. Voila, it works...
expect(username()).to.be.a('string');
});
});
you are not executing the function
change
expect(getUserName).to.be.a('string');
to
expect(getUserName()).to.be.a('string');
edit
I din't figure out that your are exporting an object
exports.getUsername = function(){...}
should be
expect(getUserName.getUserName()).to.be.a('string');
thanks to #robertklep

Error handling in Node.js for calling a function with wrong name

I am requiring a module and saving it in a variable. But when I call a module function by wrong name, it does not throw any error or consoles any error. How do I make this throw error?
var module = require('../pre_process/' + preProcessFolder + '/' + preProcessModule);
// module -> { XYZ: [Function] }
//Following does not throw error and doesn't console anything.How to handle/debug this error
module['XY'](result, userId)
.then(function(recData) {
})
I am using q library for promise.
So you want to check if a function (provided by a modul) exists.
You could use try like the example here:
Javascript check if function exists

[TypeError: Object # has no method 'replace']

First off all. I'm not posting questions about the error reason. This suddenly appeared when running an node.js app where after executing the query this error was received. I just want to know how to find the line in the source code where this error appears. How to set node to display extended info in errors like this?
So the error would be displayed like:
[TypeError: Object # has no method 'replace'] Test.js 123:98
put line 123 in try and catch the error
try{
// line 123
} catch(e){
throw e;
}
so it will print the stack of the error

Resources