SerialPort.list is not a function - node.js

I tried to create an array of port, to which serial devices are connected using the serialport module of nodeJS.
I used the following code, which should in theory work I think:
var getPortsList = (callback) => {
var portsList = [];
SerialPort.list((err, ports) => {
ports.forEach((port) => {
portsList.push(port.comName);
});
callback(null, portsList);
});
};
Whenever I execute it tho, I get the following error: TypeError: SerialPort.list is not a function.
U tried to google the problem, but could not find anything useful.
Help in any way is greatly appreciated.

SerialPort.List is deprecated from SerialPort core module and moved to SerialPort/List as a command tool.
npm install #serialport/list

Related

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

Module `fs` does not exist in the Haste module map

I'm new to Node.js and react-native. I followed the sample on send_telemetry.js exactly but when I run my react-native app I get an error: "The development server returned response error code 500.
the error message is:
bundling failed: Error: Unable to resolve module fs from ProjectPath\node_modules\azure-iot-device\lib\module_client.js: Module fs does not exist in the Haste module map";
Im running:
Node.js v10.15.3
NPM 6.4.1
react-native#0.59.2
First error was the same with Unable to resolve module events,
I can install events,
but the fs module is: "This package name is not currently in use, but was formerly occupied by another package. To avoid malicious use, npm is hanging on to the package name, but loosely, and we'll probably give it to you if you want it."
var Protocol = require('azure-iot-device-http').Http;
var DeviceClient = require('azure-iot-device').Client;
var Message = require('azure-iot-device').Message;
var connectionString = 'my connection string';
var client = DeviceClient.fromConnectionString(connectionString, Protocol);
function ConnectionTest(err) {
if (err) {
console.log('Could not connect: ' + err);
} else {
console.log('Client connected');
}
client.close(function () {
process.exit(0);
});
};
export async function Test() {
client.open(ConnectionTest);
};
Basically I need to know how to get the azure IOT hub client working in my react-native app (not using Expo).
Im pretty much stumped so any help would greatly be appreciated.
A dependency module is missing ... which is fs ...
this file-system npm module is incompatible with react-native ... cause it has it own different environment.
I had "import { symlink } from 'fs';" randomly pop up in one of my scripts. Once I deleted this line same issue you had went away. I would search your whole project for that line.

module is not defined error

I am using nodejs in my meteor app and I added packages using mrt add npm and then in my client directory in packages.json I added skimlinksjs and its version and it is added to my app.
When I tried to using them in my app in server side code like this,
var res;
var skim = Meteor.require('skimlinksjs');
var apili = Meteor.require('/config.js');
skim.setup(apili.key);
skim.query({
searchFor: "title:\"moto g\"",
fq: "country:US"
}, function(err,data) {
res=data.skimlinksProductAPI.numFound;
}
);
return res;
and my config.js file is like this
module.exports = {
key: "xxxxxxx"
}
whenI'm running this application it is showing error like
module not defined
What went wrong with my code or is there any need to install other packages?
I just got the answer
Write this function in server side code
function returnAllResult()
{
var skimlinks = Meteor.require('skimlinksjs');
skimlinks.setup("xxx");
var skimlinks_query = Async.wrap(skimlinks.query);
var result = skimlinks_query({
searchFor: "title:\"moto g\"",
fq: "country:US",
rows:5
});
return result;
}
to know about asynchronous functions watch this
and then in my server side methods call this
apiresult:function()
{
var response = returnAllResult();
return response.skimlinksProductAPI.products[0].merchant;
}
that's it working fine now. Hope this helps someone

Mongoose Trying to open unclosed connection

This is a simplified version of the problem, but basically I'm trying to open 2 mongodb connections with mongoose and it's giving me "Trying to open unclosed connection." error.
Code sample:
var db1 = require('mongoose');
db1.connect('my.db.ip.address', 'my-db');
var db2 = require('mongoose');
db2.connect('my.db.ip.address', 'my-db');
db2.connection.close();
db1.connection.close();
Any idea how to make it work?
connect() opens the default connection to the db. Since you want two different connections, use createConnection().
API link: http://mongoosejs.com/docs/api.html#index_Mongoose-createConnection
To add on Raghuveer answer :
I would also mention that instead of using mongoose directly (you are probably using it this way you end up on this post) :
require('mongoose').model(...);
You would use the returned connection :
var db = require('mongoose').connect('xxx', 'yyy');
db.model(...);
I get this issue while running my tests.
This is what I did to solve it.
//- in my app.js file.
try {
mongoose.connect('mongodb://localhost/userApi2'); //- starting a db connection
}catch(err) {
mongoose.createConnection('mongodb://localhost/userApi2'); //- starting another db connection
}
I had this problem doing unit test with mocha.
The problem came when I added a second test because beforeEach is called twice.
I've solved this with this code:
const mongoose = require('mongoose');
describe('Your test suite', () => {
beforeEach( () => {
if (mongoose.connection.db) {
return; // or done();
} else {
// connect to mongodb
});
describe('GET /some-path', () => {
it('It should...', () => {
});
});
describe('POST /some-path', () => {
it('It should...', () => {
});
});
});
Hope it helps you!
You are attempting to open the default connection ( which is not yet closed ) a 2nd time.
do the following instead
var db = require('mongoose'); //note only one 'require' needed.
var connectionToDb1 = db.createConnection('my.db1.ip.address', 'my-db1');
var connectionToDb2 = db.createConnection('my.db2.ip.address', 'my-db2');
Using mongoose.disconnect(fn):
mongoose.disconnect(() => {
// here it would be possible "reset" models to fix
// OverwriteModelError errors
mongoose.models = {};
// here comes your logic like registering Hapi plugins
server.register(somePlugin, callback);
});
I found this question typing the error message and despite my problem is a bit different I believe it could be useful for those using Hapi. More specifically Hapi + rest-hapi + mocha.
When running mocha with --watch option I was facing both: OverwriteModelError and Error: Trying to open unclosed connection errors.
Simple Solution -
Use mongoose.createConnection() instead of mongoose.connect()
Its occurs because of version issue

How to access multiple models from a controller

I have a Locations model and a Recorders model. I want to be able to pass all of the data for both data sets to my view model. How can I access them though because I think they're not in scope since I'm getting undefined errors because I'm calling 'all'
https://gist.github.com/3998302
var Main = function () {
this.index = function (req, resp, params) {
var self = this;
var data = {};
geddy.model.Locations.all(function(err, locations) {
data.locations = locations;
geddy.model.Recorders.all(function(err, recorders) {
data.recorders = recorders;
self.respond({params: params, data: data}, {
format: 'html'
, template: 'app/views/locations/index'
}
});
}););
};
};
exports.Main = Main;
Error snippet:
timers.js:103
if (!process.listeners('uncaughtException').length) throw e;
^
TypeError: Cannot call method 'all' of undefined
at index (G:\code\PeopleTracker\app\controllers\main.js:23:24)
at controller.BaseController._handleAction.callback (C:\Users\Chris\AppData\Roaming\npm\node_modules\geddy\lib\base_
controller.js:387:22)
So it looks like you're initializing the data variable to 'undefined'. Try data = {} instead. If that doesn't fix it, I'll do some troubleshooting with you.
EDIT
If that doesn't do it for you, try installing geddy again:
npm uninstall -g geddy && npm install -g geddy
If that doesn't do it, make sure that your DB is actually running, make sure that the models are defined (try geddy console to check your models), and make sure that you're on the latest stable version of node.
Very late to the party, but I believe you can just call
geddy.model.Locations.all(function(err, locations) {
geddy.model.Recorders.all(function(err, recorders) {
var data = {};
data.locations = locations;
data.recorders = recorders;
self.respond({params: params, data: data}, {
format: 'html'
, template: 'app/views/locations/index'
}
});
}););
You could also have the respond say
self.respond({params: params, locations: locations, recorders: recorders});
but if you want all of that data available from the data literal you need it defined in the lowest scope callback. The callbacks can read above their scope but they cannot write above it.

Resources