Error: Module did not self-register. (For onoff package require) - node.js

I am trying to require the package "onoff" in js file on one of he node js project. When i run a js file i get error as below
\node_modules\bindings\bindings.js:88
throw e
^
Error: Module did not self-register.
at Object.Module._extensions..node (module.js:670:18)
at Module.load (module.js:560:32)
at tryModuleLoad (module.js:503:12)
at Function.Module._load (module.js:495:3)
at Module.require (module.js:585:17)
at require (internal/module.js:11:18)
at bindings (\node_modules\bindings\bindings.js:81:44)
at Object.<anonymous> (\node_modules\epoll\epoll.js:1:99)
at Module._compile (module.js:641:30)
at Object.Module._extensions..js (module.js:652:10)
Please help through this.
Thanks in advance
Pallavi K

I've run into this issue as well and ended up mocking the library for local development. There has been a few issues created over the years, and it seems like the author either doesn't have OSX to test or he just isn't interested in supporting OSX in general.
Issues created related to this problem:
https://github.com/fivdi/epoll/issues/12
https://github.com/fivdi/onoff/issues/69
https://github.com/fivdi/onoff/issues/106
This is the work around I have:
// GpioFactory.js
class MockGPIO {
constructor(pin, direction) {
this._value = 0;
this._direction = direction;
}
readSync() { return this._value; }
read(cb) { cb(null, this._value) }
writeSync(value) { this._value = value }
write(value, cb) {
this._value = value;
cb(null, value);
}
watch(cb) {}
unwatch(cb) {}
unwatchAll() {}
direction() { return this._direction }
setDirection(direction) { this._direction = direction}
edge() { return 0; }
setEdge(edge) {}
activeLow() { return true; }
setActiveLow(invert) {}
unexport() {}
}
MockGPIO.accessible = false;
MockGPIO.HIGH = 1;
MockGPIO.LOW = 0;
module.exports = {
create: () => {
try {
return require('onoff').Gpio;
} catch (e) {
console.error('Using mock Gpio');
return MockGPIO;
}
}
};
The actual fix is the create() method that just returns the mock class. This allows my client code to use both the same way:
const GpioFactory = require('./GpioFactory');
const Gpio = GpioFactory.create();
const garageButton = new Gpio(4, 'out');
I don't use the full API of the library, so this example is likely missing some details.
Update: 12/15/2018
I submitted a PR to allow the accessible property to work on OSX as described in the docs. Hopefully it'll get merged.
PR: https://github.com/fivdi/onoff/pull/122

Related

Is this intended behaviour of custom errors?

I'm currently in the process of remaking the maze package from five years ago in ES2015. I am making a custom error, named LengthError, which will be thrown if an argument of type Function does not have a specified length. I just want to know if this is the intended behaviour because I am running this locally, or if this will carry over to production for when others might use this function?
Error:
LengthError: Argument 'adjacent' must be of length 2
/home/runner/maze/index.ts:6
throw new LengthError('Argument \'adjacent\' must be of length 2')
^
LengthError: Argument 'adjacent' must be of length 2
at null.generate (/home/runner/maze/index.ts:6:13)
at Object.<anonymous> (/home/runner/maze/index.ts:37:1)
at Module._compile (node:internal/modules/cjs/loader:1101:14)
at Object.Module._extensions..js (node:internal/modules/cjs/loader:1153:10)
at Module.load (node:internal/modules/cjs/loader:981:32)
at Function.Module._load (node:internal/modules/cjs/loader:822:12)
at Function.executeUserEntryPoint [as runMain] (node:internal/modules/run_main:81:12)
at node:internal/main/run_main_module:17:47
index.ts:
import { LengthError } from './errors';
export default function generate(nodes: number[], adjacent: Function, choose: Function) {
if (adjacent.length !== 2) {
try {
throw new LengthError('Argument \'adjacent\' must be of length 2')
} catch(e: any) {
console.error(e.name + ': ' + e.message + '\n' + e.stack)
}
}
let node: number = choose(nodes);
let stack = [node];
let maze = new Map();
for (node of nodes) {
maze.set(node, []);
}
while (node) {
let neighbors = nodes.filter(other => !maze.get(other).length && adjacent(node, other));
if (neighbors.length) {
const neighbor = choose(neighbors);
maze.get(node).push(neighbor);
maze.get(neighbor).push(node);
stack.unshift(neighbor);
node = neighbor;
} else {
stack.shift();
node = stack[0];
}
}
return maze;
}
generate([], function a() {}, function b() {});
errors.ts:
class LengthError extends Error {
constructor(message: string) {
super(message);
this.message = message;
this.name = "LengthError";
}
}
export { LengthError };
Again, is this code going to display a similar error in production (where the custom error shows twice) and will it point to the same line in my file?
I just want to know if this is the intended behaviour because I am running this locally, or if this will carry over to production for when others might use this function?
Yes, this is how it works, both locally and in production. This is what nodejs does when there's an uncaught exception using try/catch.
When you throw errors, you're supposed to have code somewhere else that catches them and turns them into the desired behavior.
In the error message, the first line is the statement of the error. The second set of lines are the "stack trace" that show where in the code this originated from, including the current call stack at the time of the error.
Note, in your code that catches exceptions, you may want to log the exception and perhaps even log the track trace and then "handle" the error in some way that makes sense for your application (such as return a user-friendly error message or in an API, return some documented API error or in an http request, return a 4xx or 5xx error status).

Smart contract deployment with node is not working

I have a problem like this. I am new to blockchain development and I have created a Smart contract using solidity. To compile it and to deploy it I have created a compile.js and deploy.js file.
This is my Solidity file.
pragma solidity 0.4.20;
contract Election {
// Model a Candidate
struct Candidate {
uint id;
string name;
uint voteCount;
}
// Store accounts that have voted
mapping(address => bool) public voters;
// Store Candidates
// Fetch Candidate
mapping(uint => Candidate) public candidates;
// Store Candidates Count
uint public candidatesCount;
// voted event
event votedEvent (
uint indexed _candidateId
);
function Election () public {
addCandidate("Candidate 1");
addCandidate("Candidate 2");
}
function addCandidate (string _name) private {
candidatesCount ++;
candidates[candidatesCount] = Candidate(candidatesCount, _name, 0);
}
function vote (uint _candidateId) public {
// require that they haven't voted before
require(!voters[msg.sender]);
// require a valid candidate
require(_candidateId > 0 && _candidateId <= candidatesCount);
// record that voter has voted
voters[msg.sender] = true;
// update candidate vote Count
candidates[_candidateId].voteCount ++;
// trigger voted event
votedEvent(_candidateId);
}
}
This is my compile.js file.
const path = require('path');
const fs =require('fs');
const solc = require('solc');
const electionPath= path.resolve(__dirname,'contracts','Election.sol');
const source = fs.readFileSync(electionPath,'utf8');
module.exports = solc.compile(source,1).contracts[':Election'];
This is my deploy.js file.
const HDWalletProvider = require('truffle-hdwallet-provider');
const Web3 = require('web3');
const { interface , bytecode } = require('./compile');
const provider = new HDWalletProvider(
'retire embark gravity flight also ceiling dinr wine example slender armor rate',
'https://rinkeby.infura.io/v3/mykey'
);
const web3 = new Web3(provider);
const deploy = async () => {
const accounts = await web3.eth.getAccounts();
console.log('Attempting to deploy from account',accounts[0]);
const result = await new web3.eth.Contract(JSON.parse(interface))
.deploy({data:bytecode})
.send({gas:'1000000',from :accounts[0]});
console.log( interface );
console.log( 'contract deploy to', result.options.address);
};
deploy();
When I hit node deploy.js in the command prompt it gives me an error like this.
TypeError: Cannot destructure property `interface` of 'undefined' or 'null'.
at Object.<anonymous> (C:\Users\tharindusa\Desktop\election\deploy.js:3:34)
at Module._compile (module.js:652:30)
at Object.Module._extensions..js (module.js:663:10)
at Module.load (module.js:565:32)
at tryModuleLoad (module.js:505:12)
at Function.Module._load (module.js:497:3)
at Function.Module.runMain (module.js:693:10)
at startup (bootstrap_node.js:191:16)
at bootstrap_node.js:612:3
Can someone help me to solve this problem? I search a lot but I was unable to find a suitable solution for this. Thank you.
I got the same error. I used solc.compile(source, 1).errors as Adam suggested and found a typo in the contract. You should try that.

Vuex without Vue?

I'd like to use Vuex to power a server-side application that doesn't use Vue. Is this possible?
const Vuex = require('vuex');
const store = new Vuex.Store({
state: {
potatoes: 1,
},
getters: {
doublePotatoes(state) {
return state.potatoes * 2;
},
},
mutations: {
addPotato(state) {
state.potatoes += 1;
},
}
});
store.watch((state, getters) => getters.doublePotatoes, console.log);
store.commit("addPotato");
Here's the error I get:
$ node index.js
/private/tmp/vtest/node_modules/vuex/dist/vuex.common.js:99
if (!condition) { throw new Error(("[vuex] " + msg)) }
^
Error: [vuex] must call Vue.use(Vuex) before creating a store instance.
at assert (/private/tmp/vtest/node_modules/vuex/dist/vuex.common.js:99:27)
at new Store (/private/tmp/vtest/node_modules/vuex/dist/vuex.common.js:279:5)
at Object.<anonymous> (/private/tmp/vtest/index.js:3:15)
at Module._compile (module.js:573:30)
at Object.Module._extensions..js (module.js:584:10)
at Module.load (module.js:507:32)
at tryModuleLoad (module.js:470:12)
at Function.Module._load (module.js:462:3)
at Function.Module.runMain (module.js:609:10)
at startup (bootstrap_node.js:158:16)
I wound up adding Vue without creating a Vue app:
const Vue = require('vue');
Vue.use(Vuex);
My tiny test store works now. I don't know if Vue.use(Vuex) without creating a Vue app will cause any problems.
Of note for server-side use cases, Vuex doesn't call my watcher for every commit; it batches changes and calls the watcher once. I don't see this documented.

Any idea what i'm doing wrong? NODEJS

...
if (response.summ > check) {
io.emit('acceptoffer', {steamid: offer.steamid_other})
helper.msg('More Than Min - ' + offer.tradeofferid);
if(timer <= 28 && timer != 0) {
offers.declineOffer({tradeOfferId: offer.tradeofferid}, function() {
currentGameOffers.splice(currentGameOffers.indexOf(offer.tradeofferid), 1);
helper.msg('Timer less than 28 seconds - ' + offer.tradeofferid);
} else {
try {
offers.acceptOffer({tradeOfferId: offer.tradeofferid}, function(err, log) {
if (err) {
...
Any idea what i'm doing wrong over here?
the error i get is that
} else {
^^^^
SyntaxError: Unexpected token else
at exports.runInThisContext (vm.js:73:16)
at Module._compile (module.js:443:25)
at Object.Module._extensions..js (module.js:478:10)
at Module.load (module.js:355:32)
at Function.Module._load (module.js:310:12)
at Function.Module.runMain (module.js:501:10)
at startup (node.js:129:16)
at node.js:814:3
What i'm trying to do is if the timer on the javascript is <=28 and <> from 0 then do offer.declineOffer and if its not run the offer.AcceptOffer.
I'm really sorry if i didnt supose to post it here and i'm also sorry for my english.
You have an open ( from offers.declineOffer and an open { from your if block. You should format your code to see the problem:
if (response.summ > check) {
io.emit('acceptoffer', {steamid: offer.steamid_other})
helper.msg('More Than Min - ' + offer.tradeofferid);
if (timer <= 28 && timer != 0) {
offers.declineOffer({tradeOfferId: offer.tradeofferid}, function () { // starts a function definition
currentGameOffers.splice(currentGameOffers.indexOf(offer.tradeofferid), 1);
helper.msg('Timer less than 28 seconds - ' + offer.tradeofferid);
} // closes the function definition
// OOPS! There's no } to close the if block.
// You also need to close the ( from offers.declineOffer
// Add the ) and } here, like this:
);
}
else
{
try {
offers.acceptOffer({tradeOfferId: offer.tradeofferid}, function (err, log) {
if (err) {
First thing first, rephrase your question before it gets too many downvotes and gets buried under, umm, something. Proper sentences are required to understand the question and intent of question, so that others can help you.
You have added else to closing brace for the function.
Instead try:
...
})
} else {
...
HTH

Exception when attempting to wrap Buffered-writer

Disclaimer: I'm fairly new to node (but not to JavaScript).
Im just trying to write a logger class, which holds a few lines at a time in memory, then flushes to disk when its buffer is reaching capacity
Problem
Calling my logger wrapper results in an exception in buffered writer
Im sure Ive misunderstood how require() works, and also various people advised me to create the object using new chatlogs.Chatlogger() but itI dont see many other node libs using this way of working
/www/im/node_modules/buffered-writer/lib/buffered-writer.js:125
cb ();
^
TypeError: undefined is not a function
at Writer.flush (/www/nodeim/node_modules/buffered-writer/lib/buffered-writer.js:125:3)
at Chatlogger.close (/www/nodeim/helpers/chatlogs.js:27:14)
at Object.<anonymous> (/www/nodeim/app.js:76:16)
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)
at startup (node.js:119:16)
at node.js:901:3
calling code...
var chatlogs = require('./helpers/chatlogs.js');
var chatlogger_obj = new chatlogs.Chatlogger();
chatlogger_obj.open("logs/log.txt");
chatlogger_obj.log("TESTING");
chatlogger_obj.close();
process.exit(0);
Wrapper class
./helpers/chatlogs.js
exports.version = '0.0.1';
var
buffer = require('buffered-writer'),
fs = require('fs');
var Chatlogger = function() {
this.handle = null,
this.filename = "",
this.dirtyops = 0;
}
Chatlogger.prototype.open = function (filename) {
//fs.unlink(filename);
this.filename = filename;
this.handle = buffer.open(filename)
.on ("error", function (error) {
//this.handle = null;
console.log (error);
});
}
Chatlogger.prototype.close = function() {
console.log("CLOSING");
this.handle.flush();
this.handle.close();
this.handle = null;
}
Chatlogger.prototype.log = function (str) {
console.log(str);
this.handle.writeln(str);
if (this.dirtyops++ > 5)
{
console.log("FLUSHING");
this.handle.flush();
this.dirtyops = 0;
}
}
module.exports.Chatlogger = Chatlogger;
I'm the author of this module. You need to pass a callback to the flush function, but you don't need to call to flush. When the buffered-writer closes or you exceed the buffer size when writing, the data is automatically flushed to disk.
Writer#flush(callback)

Resources