How to install node-hid for electron - node.js

I'm trying to get a simple electron application running that interacts with an HID device.
I am running into a lot of difficulty, I am able to install and run node-hid, just not within electron.
My package.json looks like this:
{
"name": "test-proj",
"version": "1.0.0",
"description": "",
"main": "main.js",
"scripts": {
"start": "electron .",
"rebuild": "electron-rebuild --force",
"postinstall": "electron-rebuild"
},
"author": "me",
"license": "ISC",
"devDependencies": {
"electron": "^9.2.0",
"electron-rebuild": "^1.11.0"
},
"dependencies": {
"node-hid": "^1.3.0"
}
}
My main.js has the standard electron demo boilerplate code plus some HID calls:
const {app, BrowserWindow, ipcMain} = require('electron');
var HID = require('node-hid');
var device = new HID.HID(5824, 1500);
// Standard electron app window stuff
When trying to run the app I immediately get an error on new HID.HID():
Error: Module did not self-register: '\\?\C:\Users\Nathan\Desktop\carriage_return_app\node_modules\node-hid\build\Release\HID.node'.
at process.func [as dlopen] (electron/js2c/asar.js:140:31)
at Object.Module._extensions..node (internal/modules/cjs/loader.js:1034:18)
at Object.func [as .node] (electron/js2c/asar.js:140:31)
at Module.load (internal/modules/cjs/loader.js:815:32)
at Module._load (internal/modules/cjs/loader.js:727:14)
at Function.Module._load (electron/js2c/asar.js:769:28)
at Module.require (internal/modules/cjs/loader.js:852:19)
at require (internal/modules/cjs/helpers.js:74:18)
at bindings (C:\Users\Nathan\Desktop\carriage_return_app\node_modules\bindings\bindings.js:112:48)
at loadBinding (C:\Users\Nathan\Desktop\carriage_return_app\node_modules\node-hid\nodehid.js:25:42)
Looking around I have seen a few examples of how to install node-hid and use it in electron, but none have helped me.
I have followed the electron-rebuild instructions here: https://www.electronjs.org/docs/tutorial/using-native-node-modules
I have also followed the instructions and copied the examples from here: https://github.com/node-hid/node-hid#electron-projects-using-node-hid
No luck. I get module did not self-register every time. node-hid is supposed to support electron and I don't see other people complaining.
Anyone come across this or have ideas to fix the issue?

The problem has been solved, so I will mark this as answered. I think I would still like more information on WHY though.
The hint came from building the two example projects:
https://github.com/todbot/electron-hid-toy
https://github.com/todbot/electron-hid-test
Running the first item, electron-hid-test worked off the bat. Adding electron-builder as a dependency and adding "postinstall": "electron-builder install-app-deps" as a script solved the issue in my project, I don't want electron-builder yet but at least it indicated that node-hid can work with electron given a specific setup.
The second item also worked, but not with:
npm install
npm rebuild
npm start
Instead it was specifically required to add the run command to the rebuild command:
npm install
npm run rebuild
npm start
After that, it works.
Any insights as to why this behaves differently?

Related

nodemon app crashed : Error code- MODULE_NOT_FOUND, requirestack: [ ]

When I am running nodemon run start it is giving me the following error
I am running this on macos. Not sure if that matters or not.
ERROR
node:internal/modules/cjs/loader:926
throw err;
^
Error: Cannot find module '/Users/jarvis/Documents/Backend/mongoTelusko/run'
at Function.Module._resolveFilename (node:internal/modules/cjs/loader:923:15)
at Function.Module._load (node:internal/modules/cjs/loader:768:27)
at Function.executeUserEntryPoint [as runMain] (node:internal/modules/run_main:76:12)
at node:internal/main/run_main_module:17:47 {
code: 'MODULE_NOT_FOUND',
requireStack: []
}
[nodemon] app crashed - waiting for file changes before starting...
This is my app.js file
const express = require('express')
const mongoose = require('mongoose')
const url = 'mongodb://localhost/AlienDBex'
enter code here
const app = express()
mongoose.connect(url, {useNewUrlParser: true})
const con = mongoose.connection
con.on('open', function(){
console.log('Connected...')
})
This is my package.json file
{
"name": "mongotelusko",
"version": "1.0.0",
"main": "app.js",
"scripts": {
"start": "nodemon app.js"
},
"author": "malay",
"license": "ISC",
"dependencies": {
"express": "^4.17.1",
"mongodb": "^3.6.5",
"mongoose": "^5.12.2"
},
"devDependencies": {
"nodemon": "^2.0.7"
},
"description": ""
}
"scripts": {
"start": "nodemon app.js"
},
Since you have specified "start" script in package.json, npm start command automatically calls nodemon app.js
However, you can also run the nodemon app.js manually which also has the same effect.
Wrong: nodemon run start
Correct: nodemon app.js or npm start
You're running nodemon run start, which tells nodemon to execute run (run.js) with argument start. Did you mean to use npm run start? Hint: You can also use npm start as a shortcut.
I've got the same error while I'm trying to run the code on my Mac.
I found why it is showing me this error:
first reason is that I've installed Node.js through an installation pack downloaded from [nodejs.org][1], but I should've installed node from the Terminal.
second reason is that I found out that I was trying to run the file from a different folder. I was in folder /users/practice/file-manager/frontend - trying to run the code from file which is located in directory /users/practice/file-manager/backend - the main reason which caused this error.
As a solution that worked for me:
make sure you've installed Node.js from terminal
make sure you're in the right directory when you're trying to run the .js file.
Maybe this information helps you.
My solution after trying new files, etc... didnt work. Then starting from the beginning:
deleting node.js and clearing cache about npm (from appdata)
creating new file and being sure about path you can confirm with 'cd'
trying to re-install npm_modules at my project folder.(npm install)
Then it worked.

ElectronJS build doesn't include needed folder

I'm working on a ElectronJS and ExpressJS project to build an application that runs an API in background and show a system tray with some features to control and monitor that API.
"electron": "^4.0.4",
"electron-builder": "^20.38.5",
I use electron-builder to generate an installer for macOS, and Windows (.exe with nsis and .dmg) packages containing my express API built app as it is.
That's mean, I build it separately and call it's entry point build/index.js in my electron's main.js, Despite, that hook and everything else is fine in development env. But when i run the build, it show me that error:
A JavaScript error occurred in the main process
Uncaught Exception:
Error: Cannot find module 'express'
at Module._resolveFilename (internal/modules/cjs/loader.js:584:15)
at Function.Module._resolveFilename (/Users/username/WebstormProjects/my-api-monitor/release/mac/API monitor.app/Contents/Resources/electron.asar/common/reset-search-paths.js:43:12)
at Function.Module._load (internal/modules/cjs/loader.js:510:25)
at Module.require (internal/modules/cjs/loader.js:640:17)
at require (internal/modules/cjs/helpers.js:20:18)
at Object.<anonymous> (/Users/username/WebstormProjects/my-api-monitor/release/mac/API monitor.app/Contents/Resources/app/api/build/index.js:19:16)
at Object.<anonymous> (/Users/username/WebstormProjects/my-api-monitor/release/mac/API monitor.app/Contents/Resources/app/api/build/index.js:208:3)
at Module._compile (internal/modules/cjs/loader.js:693:30)
at Object.Module._extensions..js (internal/modules/cjs/loader.js:704:10)
at Module.load (internal/modules/cjs/loader.js:602:32)
I guess the problem is that the node_modules of my API in /build folder isn't packaged in the app, and i can't achieve that with the normal way documented in electron-builder readme.
For more details, here is my files tree.
Also, my electron-builder config. :
"asar": false,
"files": [
"main.js",
"api/**/*",
"resources/**/*"
],
"directories": {
"buildResources": "resources",
"output": "release"
}
Same issue with or without asar, i jsut keep it false to check if folders and files are included right.
Any idea will be helpful.

npm script: browser opened using node, but not using babel

Early days in the development of my first npm script, and struggling somewhat. I'm on Ubuntu LTS with the latest nvm, node, npm and pnpm releases.
Node + npm have been installed using nvm, pnpm installed using npm, and several modules installed locally (i.e. without the -g flag) using pnpm. No sudo was necessary. The resulting package.json:
{
"name": "javascript-development-environment",
"version": "1.0.0",
"description": "JavaScript development environment cobbled together using various online sources",
"scripts": {
"prestart": "./node_modules/.bin/babel buildScripts/startMessage.js",
"start": "./node_modules/.bin/babel buildScripts/srcServer.js"
},
"author": "Laird o' the Windy Waas",
"license": "MIT",
"dependencies": {
"#babel/polyfill": "^7.0.0"
},
"devDependencies": {
"#babel/cli": "^7.1.5",
"#babel/core": "^7.1.6",
"#babel/preset-env": "^7.1.6",
"chalk": "^2.4.1",
"express": "^4.16.4",
"open": "^0.0.5",
"path": "^0.12.7"
}
}
With only Firefox 60.0.1 installed, on doing a 'pnpm start' using node, a browser window is opened "Hello World!" displayed, and terminal control has to be regained using a CTRL-C. -> All ok.
If I substitute in babel using the path as shown above (which results from the same issues described in this post), the buildScripts code is echoed to the terminal, but no browser window opens, and terminal control is released immediately on completion. The npm debugger provides no useful feedback. -> Something not working..
As the "Hello World!" code is traversed correctly using node (and remains unchanged for the babel traversal), it is not the source of the problem.
Here my babel config files:
.babelrc
{
"presets": [
"#babel/preset-env"
]
}
babel.config.js
const presets = [
[
"#babel/env",
{
targets: {
edge: "17",
firefox: "61",
chrome: "67",
safari: "11.1",
opera: "56"
},
useBuiltIns: "usage"
},
],
];
module.exports = { presets };
The problem looks to be that babel is not passing the transpiled code on to nodejs / express. Bound to be something simple, but I'm just going round in circles..
One thing I found myself asking is whether there might be a conflict between the various env presets across .babelrc, babel.config.js and package.json. Successive parking of the .babelrc and babel.config.js files, however, brought no change/advance.
I have also noticed that both (nvms) node and (ubuntus) nodejs are currently installed:
$ which node
/home/<myusername>/.nvm/versions/node/v10.13.0/bin/node
$ which nodejs
/usr/bin/nodejs
However, as everything to do with node and npm was installed using nvm, this shouldn't be a problem.
I could, I suppose, try installing babel globally, but with this widely frowned apon. I'd prefer a solution reflecting 'best practice'.
Thanks for any suggestions.
In earlier years, tutor material suggested babel-node would start npm / node (and hence express) on the user's behalf.
babel-node now no longer seems to be recognised. Attempts at using the babel-node command failed, and simply using node in it's place resulted in the transpiler output being dumped to the terminal.
babel, (in our case) pnpm, and node now have to be explicitly called, the latter referencing the transpiled code. node appears to handle interfacing with express.
After some experiment, therefore, the following changes (in package.json) appear to work fine:
"scripts": {
"prestart": "./node_modules/.bin/babel buildScripts/startMessage.js -d dist",
"build": "./node_modules/.bin/babel buildScripts/srcServer.js -d dist",
"start": "pnpm run build && node dist/startMessage.js && node dist/srcServer.js"
},
These result both in a tidy console output and result in "Hallo World!" being displayed in a freshly opened browser window.
Just hope this is of use to someone else.. ;-)

unexpected token error with NPM? [duplicate]

I was experimenting on using Node version 6.2.1 with some of my code. Had plans to migrate most of the hyper-callback oriented codes to something that looks cleaner and maybe performs better.
I have no clue why, the terminal throws up an error when I try to execute the node code.
helloz.js
(async function testingAsyncAwait() {
await console.log("Print me!");
})();
Logs-
BOZZMOB-M-T0HZ:rest bozzmob$ node helloz.js
/Users/bozzmob/Documents/work/nextgennms/rest/helloz.js:1
(function (exports, require, module, __filename, __dirname) { (async function testingAsyncAwait() {
^^^^^^^^
SyntaxError: Unexpected token function
at Object.exports.runInThisContext (vm.js:53:16)
at Module._compile (module.js:513:28)
at Object.Module._extensions..js (module.js:550:10)
at Module.load (module.js:458:32)
at tryModuleLoad (module.js:417:12)
at Function.Module._load (module.js:409:3)
at Function.Module.runMain (module.js:575:10)
at startup (node.js:160:18)
at node.js:456:3
BOZZMOB-M-T0HZ:rest bozzmob$ node -v
v6.2.1
What am I missing? Please throw me some light on the same.
Update 1:
I tried to use Babel as Quentin suggested, But, I am getting the following error still.
Updated Code-
require("babel-core/register");
require("babel-polyfill");
(async function testingAsyncAwait() {
await console.log("Print me!");
})();
Logs-
BOZZMOB-M-T0HZ:rest bozzmob$ babel helloz.js > helloz.trans.js
SyntaxError: helloz.js: Unexpected token (3:7)
1 | require("babel-polyfill");
2 |
> 3 | (async function testingAsyncAwait() {
| ^
4 | await console.log("Print me!");
5 | })();
Async functions are not supported by Node versions older than version 7.6.
You'll need to transpile your code (e.g. using Babel) to a version of JS that Node understands if you are using an older version.
That said, versions of Node.js which don’t support async functions are now all past End Of Life and are unsupported, so if you are using an earlier version you should very strongly consider upgrading.
Nodejs supports async/await from version 7.6.
Release post: https://v8project.blogspot.com.br/2016/10/v8-release-55.html
Node.JS does not fully support ES6 currently, so you can either use asyncawait module or transpile it using Babel.
install
npm install --save asyncawait
helloz.js
var async = require('asyncawait/async');
var await = require('asyncawait/await');
(async (function testingAsyncAwait() {
await (console.log("Print me!"));
}))();
If you are just experimenting you can use babel-node command line tool to try out the new JavaScript features
Install babel-cli into your project
$ npm install --save-dev babel-cli
Install the presets
$ npm install --save-dev babel-preset-es2015 babel-preset-es2017
Setup your babel presets
Create .babelrc in the project root folder with the following contents:
{ "presets": ["es2015","es2017"] }
Run your script with babel-node
$ babel-node helloz.js
This is only for development and testing but that seems to be what you are doing. In the end you'll want to set up webpack (or something similar) to transpile all your code for production
babel-node sample code : https://github.com/stujo/javascript-async-await/tree/15abac
If you want to run the code somewhere else, webpack can help and here is the simplest configuration I could work out:
Full webpack example : https://github.com/stujo/javascript-async-await
node v6.6.0
If you just use in development. You can do this:
npm i babel-cli babel-plugin-transform-async-to-generator babel-polyfill --save-dev
the package.json would be like this:
"devDependencies": {
"babel-cli": "^6.18.0",
"babel-plugin-transform-async-to-generator": "^6.16.0",
"babel-polyfill": "^6.20.0"
}
create .babelrc file and write this:
{
"plugins": ["transform-async-to-generator"]
}
and then, run your async/await script like this:
./node_modules/.bin/babel-node script.js
Though I'm coming in late, what worked for me was to install transform-async-generator and transform-runtime plugin like so:
npm i babel-plugin-transform-async-to-generator babel-plugin-transform-runtime --save-dev
the package.json would be like this:
"devDependencies": {
"babel-plugin-transform-async-to-generator": "6.24.1",
"babel-plugin-transform-runtime": "6.23.0"
}
create .babelrc file and write this:
{
"plugins": ["transform-async-to-generator",
["transform-runtime", {
"polyfill": false,
"regenerator": true
}]
]
}
and then happy coding with async/await
include and specify the node engine version to the latest, say at this time I did add version 8.
{
"name": "functions",
"dependencies": {
"firebase-admin": "~7.3.0",
"firebase-functions": "^2.2.1",
},
"engines": {
"node": "8"
},
"private": true
}
in the following file
package.json

Have you got nightmareJS working properley on c9.io IDE

NightmareJS on c9.io is literally a nightmare.
i cannot get it to work at all i am going to run through the whole process from start to finish.
Step 1
I create a new workspace
Hosted
Node.js
Step 2
Start Editing my new workspace
I open Package.json and add what i need heres my file.
{
"name": "chat-example",
"version": "0.0.0",
"description": "A chat example to showcase how to use `socket.io` with a static `express` server",
"main": "server.js",
"repository": "",
"author": "Mostafa Eweda <mostafa#c9.io>",
"dependencies": {
"async": "~0.2.8",
"express": "~3.2.4",
"socket.io": "~0.9.14",
"phantomjs": "*",
"casperjs": "*",
"nightmarejs": "*",
"utils": "*",
"crypto": "*"
}
}
i then run 'npm install' in the console.
Step 3
this is where it does not work i try all theses diffrent commands to get the examples running and the errors i get.
#stackoverflow:~/828481 $ cd node_modules/nightmarejs/examples/
#stackoverflow:~/828481/node_modules/nightmarejs/examples $ node server.js casper.js
Error: Cannot find module 'crypto'
phantomjs://bootstrap.js:289
phantomjs://bootstrap.js:254 in require
/var/lib/stickshift/5345392f50044693d40008de/app-root/data/828481/node_modules/utils/utils.js:7
/var/lib/stickshift/5345392f50044693d40008de/app-root/data/828481/node_modules/utils/utils.js:117
/var/lib/stickshift/5345392f50044693d40008de/app-root/data/828481/node_modules/utils/utils.js:118
Error: Cannot find module 'casper'
phantomjs://bootstrap.js:289
phantomjs://bootstrap.js:254 in require
/var/lib/stickshift/5345392f50044693d40008de/app-root/data/828481/node_modules/nightmarejs/lib/nightmareClient.js:4
/var/lib/stickshift/5345392f50044693d40008de/app-root/data/828481/node_modules/nightmarejs/lib/nightmareClient.js:83
TypeError: 'undefined' is not a function (evaluating 'require(phantom.args[3].slice(13)+'nightmareClient.js').Nightmare({
exitOnError: false
})')
/var/lib/stickshift/5345392f50044693d40008de/app-root/data/828481/node_modules/nightmarejs/lib/nightmareTest.js:16
I have it working. I also had trouble at first. I tried downloading the prebuilt package, but I can't seem to get that working. I ended up just adding the following to my package.json file and ran npm update and all was well:
"nightmare": "^1.5.0",
"phantomjs": "~1.9.7"
Probably they've updated the npm repo and everything since you've posted this. I bet it was frustrating. I don't have those examples in my install, but I would guess you could run them if you had all of the right pre-req's installed.

Resources