How to send data to USB device in node.js using libusb - javascript

I have try to get data from device (USB thermometer), following this documentation, but I have not any result.
For getting themperature data from device, I should send the data like that 'd\n'.
This is my code:
var usb = require('usb'),
term = usb.findByIds(65535, 2);
term.open();
var endpoints = term.interfaces[0].endpoints,
inEndpoint = endpoints[0],
outEndpoint = endpoints[1];
inEndpoint.transferType = 2;
inEndpoint.startStream(1, 64);
inEndpoint.transfer(64, function (error, data) {
if (!error) {
console.log(data);
} else {
console.log(error);
}
});
inEndpoint.on('data', function (data) {
console.log(data);
});
inEndpoint.on('error', function (error) {
console.log(error);
});
outEndpoint.transferType = 2;
outEndpoint.startStream(1, 64);
outEndpoint.transfer(new Buffer('d\n'), function (err) {
console.log(err);
});
After running I have got this:
D:\Dev\USBTest\node_modules\usb\usb.js:261
t.submit(new Buffer(self.streamTransferSize), transferDone)
^
Error: LIBUSB_ERROR_NOT_FOUND
at startTransfer (D:\Dev\USBTest\node_modules\usb\usb.js:261:5)
at Array.forEach (native)
at InEndpoint.startStream (D:\Dev\USBTest\node_modules\usb\usb.js:264:23)
at D:\Dev\USBTest\app.js:15:16
at Object.<anonymous> (D:\Dev\USBTest\app.js:35:2)
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)
at Function.Module.runMain (module.js:497:10)

You forgot to call interface.claim().
https://github.com/nonolith/node-usb#claim

The interface should be declared using the term.interface(interfaceId) method, not term.interfaces[0]
https://www.npmjs.com/package/usb#interfaceinterface

Use sudo before running your command.
Wrong:
node index.js
Right:
sudo node inex.js

Related

How to add information on a try catch error chain, for a comprehensive stack trace? [duplicate]

This question already has answers here:
JavaScript / TypeScript : Standard way to keep the cause of an Error
(3 answers)
Closed 3 months ago.
Taken this code:
try {
try {
try {
throw new Error(`ERR00`)
} catch (error) {
throw new Error(`ERR01`)
}
} catch (error) {
throw new Error(`ERR03`)
}
} catch (error) {
console.log(error, (error as Error).stack);
}
The stack output will only report the most external error (topmost) but not the error chain.
Now imagine this error chain happen on distinct places func03 calls func02 calls func01
otherwise solution might be simple and wrap everything on a single trycatch.
Stack will only report error for func03 and will not be straightforward to backtrace the error. Without additional logging.
Like:
Error: ERR00
at Object.<anonymous> (/[...]/test.ts:4:15)
at Module._compile (internal/modules/cjs/loader.js:1085:14)
at Module.m._compile (/usr/local/lib/node_modules/ts-node/src/index.ts:858:23)
at Module._extensions..js (internal/modules/cjs/loader.js:1114:10)
at Object.require.extensions.<computed> [as .ts] (/usr/local/lib/node_modules/ts-node/src/index.ts:861:12)
at Module.load (internal/modules/cjs/loader.js:950:32)
at Function.Module._load (internal/modules/cjs/loader.js:790:12)
at Function.executeUserEntryPoint [as runMain] (internal/modules/run_main.js:76:12)
at main (/usr/local/lib/node_modules/ts-node/src/bin.ts:227:14)
at Object.<anonymous> (/usr/local/lib/node_modules/ts-node/src/bin.ts:513:3) Error: ERR00
at Object.<anonymous> (/Users/nicola.aretini/Documents/github/nms-backend-services/nms.productful/test.ts:43:15)
at Module._compile (internal/modules/cjs/loader.js:1085:14)
at Module.m._compile (/usr/local/lib/node_modules/ts-node/src/index.ts:858:23)
at Module._extensions..js (internal/modules/cjs/loader.js:1114:10)
at Object.require.extensions.<computed> [as .ts] (/usr/local/lib/node_modules/ts-node/src/index.ts:861:12)
at Module.load (internal/modules/cjs/loader.js:950:32)
at Function.Module._load (internal/modules/cjs/loader.js:790:12)
at Function.executeUserEntryPoint [as runMain] (internal/modules/run_main.js:76:12)
at main (/usr/local/lib/node_modules/ts-node/src/bin.ts:227:14)
at Object.<anonymous> (/usr/local/lib/node_modules/ts-node/src/bin.ts:513:3)
How do you recommend to use Error class to fill up correctly the stack trace ?
To get something like:
Error: ERR03
at Object.<anonymous> (/[...]/test.ts:4:15)
Error: ERR02
at Object.<anonymous> (/[...]/test.ts:6:15)
Error: ERR01
at Object.<anonymous> (/[...]/test.ts:8:15)
....
This is what the .cause error property (see the old proposal page for more details) is meant to do:
try {
try {
try {
throw new Error(`ERR00`)
} catch (error) {
throw new Error(`ERR01`, {cause: error})
}
} catch (error) {
throw new Error(`ERR03`, {cause: error})
}
} catch (error) {
console.error(error);
}

cant catch code breaking error thrown inside required class

im trying to scrap a website using pupeteer , this website has captcha and i use a 3rd party library/api to bypass the captcha
here is the simplified version of my code
const puppeteer = require('puppeteer');
const dbc = require('./dpc/deathbycaptcha');
async function init()
{
let page = launchPuppeteer();
try {
await page.goto(`https://www.example.com`, {timeout: 60000});
await captcha_element.screenshot({ path: setting.captcha , omitBackground: true, });
let captchaResult = await solve_captcha().catch((error)=> {throw new Error( error) });
log('ALL DONE');
}
catch (e) {
log('=====================ERROR============================');
log(e);
}
}
here is solve_captcha function
function solve_captcha(){
return new Promise(( resolve , reject )=>{
try
{
const client = new dbc.HttpClient('myUsername', 'myPassword');
client.decode({captcha: setting.captcha}, (captcha) => {
if (captcha) {
resolve(captcha['text']);
}
else
{
reject('error')
}
});
}
catch (e) {
reject(e.toString());
}
})
}
so sometimes i cant connect to captcha solving api due to down server or network problems , it would throw this error
C:\pathToProject\dpc\deathbycaptcha.js:218
throw new Error(err.message);
^
Error: read ECONNRESET
at ClientRequest.<anonymous> (C:\pathToProject\dpc\deathbycaptcha.js:218:15)
←[90m at ClientRequest.emit (events.js:310:20)←[39m
←[90m at Socket.socketErrorListener (_http_client.js:426:9)←[39m
←[90m at Socket.emit (events.js:310:20)←[39m
←[90m at emitErrorNT (internal/streams/destroy.js:92:8)←[39m
←[90m at emitErrorAndCloseNT (internal/streams/destroy.js:60:3)←[39m
←[90m at processTicksAndRejections (internal/process/task_queues.js:84:21)←[39m
this error happens in the deathbycaptcha.js which i've required in my code with
const dbc = require('./dpc/deathbycaptcha');
here is the simplified version of the code in the in the deathbycaptcha.js which is cuzing the error
class HttpClient extends Client {
_call(arguments here) {
var options = {someoptions};
var form = new FormData();
const request = form.submit(options, (err, response) => {
if (err) {
console.log(err.toString())
throw new Error(err.message);
}
// more code here
}
}
so here is the problem , i have this code running inside 2 try/catch blocks
first in the caller function (init()) and second one in the solve_captcha function but none of them are able to catch this error and it will break all the code and the program will exit and i have to run it again
why cant i catch and handle this error in my code ?

nodeJS returns Type Error when creating a file using fs writeFile

I've just started learning nodeJS. I'm at a very basic level.
Right now I'm working with creating new files and directories methods.
This is my Code -
var fs = require('fs');
fs.mkdir("stuff", function () {
fs.readFile('readMe.txt', 'utf8', function (err, data){
fs.writeFile('./stuff/writeMe.txt', data);
});
});
It does create the directory and does read the file, but doesn't create a new file.
I checked the code times and again, but the terminal is returning this error.
fs.js:152
throw new ERR_INVALID_CALLBACK(cb);
^
TypeError [ERR_INVALID_CALLBACK]: Callback must be a function. Received undefined
[90m at maybeCallback (fs.js:152:9)[39m
[90m at Object.writeFile (fs.js:1351:14)[39m
at D:\PRANAV\Learning Folder\Node\app.js:6:12
[90m at FSReqCallback.readFileAfterClose [as oncomplete] (internal/fs/read_file_context.js:63:3)[39m {
code: [32m'ERR_INVALID_CALLBACK'[39m
}
I'm stuck at this, please help.
fs.writeFile's last argument should be a callback function. Right now, you're missing it:
fs.mkdir("stuff", function () {
fs.readFile('readMe.txt', 'utf8', function (err, data) {
fs.writeFile('./stuff/writeMe.txt', data, function (err) {
if (err) {
throw err;
}
console.log('written successfully!');
});
});
});

Can not call another REST request in mongoose findOne() NodeJS

I'm newbie in NodeJS. I used Mongoose to check the existing item, if the item is not exist then will call another REST API, but it throw the error when running.
//check if hotel is existing
HotelModel.findOne({ name: hotel.name }, { name: 1 }, function (err, result) {
if (err) {
return
}
if (result) {
return
}
var address = await getHotelAddress(hotel.id) => throw error
});
and here is the error log:
var address = await getHotelAddress(hotel.id)
^^^^^^^^^^^^^^^
SyntaxError: Unexpected identifier
at createScript (vm.js:80:10)
at Object.runInThisContext (vm.js:139:10)
at Module._compile (module.js:607:28)
at Object.Module._extensions..js (module.js:654:10)
It seems to can not call another task in findOne.
Thanks in advance.

Javascript: buffer.js:202 Rest call throw new TypeError(kFromErrorMsg)

Trying to perform first Rest call using javascript. My code is below:
var https = require('https');
var user = '<Domain>\\*****';
var pass = '******';
process.env.NODE_TLS_REJECT_UNAUTHORIZED = "0";
/**
* HOW TO Make an HTTP Call - GET
*/
// options for GET
var optionsget = {
host : '**************', // here only the domain name
// (no http/https !)
port : 443,
path : '/rest/api/latest/plan/dummy1/branch', // the rest of the url with parameters if needed
method : 'GET', // do GET
'Content-Type': 'application/json',
Accept: 'application/json',
auth : {
username: user,
password: pass
}
};
console.info('Options prepared:');
console.info(optionsget);
console.info('Do the GET call');
// do the GET request
var reqGet = https.request(optionsget, function(res) {
console.log("statusCode: ", res.statusCode);
// uncomment it for header details
console.log("headers: ", res.headers);
res.on('data', function(d) {
console.info('GET result:\n');
process.stdout.write(d);
console.info('\n\nCall completed');
});
});
reqGet.end();
reqGet.on('error', function(e) {
console.error(e);
});
However above is generating error as below. Please help to understand this issue and how to fix it?
Do the GET call
***buffer.js:202
throw new TypeError(kFromErrorMsg);
^
TypeError: First argument must be a string, Buffer, ArrayBuffer, Array, or array-like object.
at Function.Buffer.from (buffer.js:202:9)
at new ClientRequest (_http_client.js:198:27)
at Object.request (http.js:38:10)
at Object.request (https.js:239:15)
at Object.<anonymous> (C:\som_temp\test.js:49:20)
at Module._compile (module.js:643:30)
at Object.Module._extensions..js (module.js:654:10)
at Module.load (module.js:556:32)
at tryModuleLoad (module.js:499:12)
at Function.Module._load (module.js:491:3)***

Categories

Resources