I want to emit events from my Nodejs module but it's not working as expected as we are getting an error:
Uncaught TypeError: Test.on(...) is not a function.
Here is the module test.js
var util = require("util");
var EventEmitter = require("events").EventEmitter;
function Test() {
EventEmitter.call(this);
}
Test.prototype.test = function (input) {
this.emit("testevent", input);
};
util.inherits(Test, EventEmitter);
module.exports = Test;
And in the index.js we have the following:
const Test = new (require('./test.js'));
Test.on('testevent', function (test) {
console.log('emitted', test);
});
// Test.test('input');
I understand with just that code in index.js the event should never get emitted since Test.test('input'); is not called.
However, with that line disabled, I am confused about why I am getting Uncaught TypeError: Test.on(...) is not a function.
The error goes away once Test.test('input'); is uncommented and the event appears to emit as I can see the logged line. But why? Why is it throwing that error if the line is disabled? What are we doing wrong?
Using const Test = new (require('test.js')); you are require test.js module from node_modules and there is one because you don't have MODULE_NOT_FOUND error, but is this a file you really want to require, or maybe this should be local file with realative path const Test = new (require('./test.js'));
After uncommenting this line Test.test('input'); this is unlikely to log anything because this code emits test event and your code is listening for testevent only.
In general this code works well, here is a example https://repl.it/repls/DiscreteUnwrittenNet
Related
Here is the error:
logPunishment(target.id, logObj)
^
TypeError: logPunishment is not a function
Code:
bot/components/ban.js
const { logPunishment } = require('../db.js')
logPunishment(input1, input2)
some code of:
bot/db.js:
async function logPunishment(userId, punishmentObject){
data = await User.findOne({id: userId})
if (!data){
await User.create({id: userId, punishments: []})
data = await User.findOne({id: userId})
}
punishments = data.punishments
punishments.push(punishmentObject)
User.updateOne({id: userId, punishments: punishments})
}
module.exports.logPunishment = logPunishment
logPunishment is clearly a function, but why does it say its not a function?
After console.log(logPunishment) this is the result:
undefined
why is that I couldn't understand. Please help!
What can I do to fix it now?
There are no other errors(for now) apart this
Please someone help!!!
I have tried this as per a answer
const logPunishment = require('../db.js').logPunishment,
which didn't work
Also I'm getting this warning after running the program:
(node:40712) Warning: Accessing non-existent property 'logPunishment' of module exports inside circular dependency
I m not overiding any exports, I have confirmed it.
TL;DR it's because of your circular dependency. Consider the following two files in the same directory:
a.js
const { b } = require('./b');
module.exports.a = 'hello world';
console.log(b());
and b.js
const { a } = require('./a.js');
function b() {
return a;
}
module.exports.b = b;
If you run node a.js you'll see the circular dependency error
(node:9235) Warning: Accessing non-existent property 'a' of module exports inside circular dependency
If you run node b.js you'll see
TypeError: b is not a function
This has to do with how requires get resolved when there are circular dependencies. If you run a then it requires b which requires a which means b gets a's unfinished exports, so you'll see undefined print instead of hello world. If you run b you'll get b's unfinished exports in a which means that you'll be calling undefined as a function
You can fix it by moving the things that b requires from a into a different file: there's not really a good reason to use circular dependencies.
I have an error:
TypeError: Cannot read propety 'send' of undefind on start of my program. How to correctly trigger app.on without errors?
import * as electron from "electron";
const {app, BrowserWindow,ipcRenderer,ipcMain} = electron;
var correspondingWindow = null;
let mainWindow;
ipcMain.on('newWindow', function (e, category) {
//some code with switch Window_1
});
app.on('ready', function () {
"use strict";
ipcRenderer.send('newWindow', 'Window_1');
});
I feel like this is probably a dupe of another question, but ipcRenderer cannot be used in the main process. See the docs which say:
Process: Renderer
If you want to send a message from the main process to the main process, you can use ipcMain.emit, or just call the function directly. Why send messages in this case?
I'm using remark-math to render maths equations from Markdown. This has previously been working without a hitch, however after I refactored some seemingly unrelated code, I now get the following exception:
Uncaught ReferenceError: INLINE_MATH_DOUBLE is not defined
at Of.inlineTokenizer (inline.js:12)
at Of.tokenize [as tokenizeInline] (tokenizer.js:111)
at Of.atxHeading (heading-atx.js:148)
at Of.tokenize [as tokenizeBlock] (tokenizer.js:111)
at Of.parse (parse.js:41)
at Function.parse (index.js:275)
at pipelineParse (index.js:22)
at wrapped (index.js:93)
at next (index.js:56)
at Object.run (index.js:30)
The relevant code from ./node_modules/remark-math/inline.js looks like the following:
const ESCAPED_INLINE_MATH = /^\\\$/
const INLINE_MATH = /^\$((?:\\\$|[^$])+)\$/
const INLINE_MATH_DOUBLE = /^\$\$((?:\\\$|[^$])+)\$\$/ // << defined here?
module.exports = function inlinePlugin (opts) {
function inlineTokenizer (eat, value, silent) {
let isDouble = true
let match = INLINE_MATH_DOUBLE.exec(value) // << line 12, error here
// ...remaining code
The constant appears to be defined in scope!
I'm building using webpack and the chentsulin/electron-react-boilerplate template. Any hints as to why this kind of exception would suddenly be happening? (I've tried a complete reinstall of node_modules.)
maybe some issues happen from webpack building.
if the error still happen, and you want to avoid it, you can use this
GLOBAL.INLINE_MATH_DOUBLE = /^\$\$((?:\\\$|[^$])+)\$\$/
I reinstalled the dependencies with yarn instead of npm and the issue went away.
I'm trying to use your relaxed-json in my Electron app. Here is a simple code, GetDeviceList() is triggered on a button-push action:
const driver = require('meteor_driver').MeteorConnection.MeteorConnection;
const relaxed = require('relaxed-json');
const connection = new driver();
function GetDeviceList() {
console.log(connection.port);
console.log("Launching");
console.log(relaxed);
relaxed.transform('[{id:0,},{id:1,},{id:2,},]');
}
The console.log show me an empty object. And I got an error message Uncaught TypeError: relaxed.transform is not a function.
Otherwise, the package works properly when it's not used with electron.
Note that I don't encounter any require-related issue, so the modules must be valid isn't ?
I am creating HTTP tests with frisby.js which works on top of jasmine.js.
I also have to create some mongoDB objects to test against.
The problem is when I want to clean up these DB objects. When one of the expects fail I want to intercept that and call my own cleanup function. This means that after each failed test, I won't be able to remove the test objects from the DB.
The afterEach function in jasmine does not work properly and jasmine does not have any support for afterAll or beforeAll yet.
That is why I have made the tests as they are today.
it("testing userform get with correct userID and expect correct return", function() {
var innerUserId = userID;
frisby.create('Should retrieve correct userform and return 200 when using a valid userID')
.get(url.urlify('/api/userform', {id: innerUserId}))
.expectStatus(200)
.afterJSON(function(userform){
// If any of these fail, the after function wont run.
// I want to intercept the error so that I can make sure that the cleanUp function is called
// afterEach does not work. I have tried with done()
var useridJSON = userform.UserId.valueOf();
var firstnameJSON = userform.firstname.valueOf();
var surnameJSON = userform.surname.valueOf();
expect(firstnameJSON).toMatch(testUser.firstName);
expect(surnameJSON).toMatch(testUser.surname);
expect(useridJSON).toMatch(innerUserId);
})
.after(function(){
cleanUp(innerUserId);
})
.toss();
});
I am wondering if there is a way to intercept the error for "expect" in frisby or jasmine so that I can make a call to my own cleanup function before exiting.
Full example here
The quickest solution to this problem is to wrap the error code in a try-catch.
This is because if a javascript error occurs, jasmine will NOT keep running assertions. This is different from an assertion error. If an assertion error occurs, jasmine and frisby will keep on testing all the other assertions and then do the "after"-function.
.afterJSON(function(userform){
try {
var useridJSON = userform.UserId.valueOf();
var firstnameJSON = userform.firstname.valueOf();
var surnameJSON = userform.surname.valueOf();
catch(e) {
cleanUp(innerUserId);
// Can do a throw(e.message); here aswell
}
expect(firstnameJSON).toMatch(testUser.firstName);
expect(surnameJSON).toMatch(testUser.surname);
expect(useridJSON).toMatch(innerUserId);
})
This is not the pretty way, but works.
I ended up adding the throw(e) and placed the expects in a finally scope. This way I got jasmine to present all the errors that occured in the test.
As for "before exiting", how about this:
process.on('uncaughtException', function(err) {
console.error(' Caught exception: ' + err);
});