Issue with module wrapper function - node.js

I'm trying to learn node.js, and having an issue with running a code with module wrapper function. Here is the code
logger.js (1)
var url = 'http://mylogger.io/log';
function log(message) {
console.log(message);
}
module.exports.log = log;
logger.js(2)
( function (exports, require, module, __filename, __dirname)
{
var url = 'http://mylogger.io/log';
function log(message) {
console.log(message);
}
module.exports.log = log;
})
app.js
const logger = require('./logger.js')
console.log(logger);
logger.log('Hiya');
The logger.js(1) works fine, logger.js(2) gives out following error.
TypeError: logger.log is not a function
at Object.<anonymous> ()
at Module._compile (node:internal/modules/cjs/loader:1092:14)
at Object.Module._extensions..js (node:internal/modules/cjs/loader:1121:10)
at Module.load (node:internal/modules/cjs/loader:972:32)
at Function.Module._load (node:internal/modules/cjs/loader:813:14)
at Function.executeUserEntryPoint [as runMain] (node:internal/modules/run_main:76:12)
at node:internal/main/run_main_module:17:47
I was expecting to get the same result from both cases

In the snippet which you have attached as logger.js(2),
function (exports, require, module, __filename, __dirname) is irrelevant and does not make sense to the NodeJS Compiler.
The correct way of doing what you expect is the one listed in logger.js(1)
If you are exporting multiple functions then,
var url = 'http://mylogger.io/log';
function log(message) {
console.log(message);
}
function log_twice(message) {
console.log(message);
console.log(message);
}
module.exports = { log: log, log_twice: log_twice }; //and so on
Request to accept the answer if it helps...

Related

How to bundle worker_thread dependencies with webpack

I'm writing an electron application that uses electron forge for setup and configuration.
The project uses Webpack 5 as a bundler and typescript as the development language. I'm having trouble running a worker_thread on the main-thread.
It all works fine, as long as the worker_thread does not use any imported local modules. But when I import modules they can't be found. I'm thinking this is because webpack doesn't bundle the dependencies from the worker.
My code looks like this:
index.ts (electron main thread):
ipcMain.handle('export', async (event, measurements: Measurement[], options: ExportOptions) => {
return new Promise((resolve, reject) => {
const worker = new Worker(new URL('./export.worker.js', import.meta.url))
worker.on('message', resolve)
worker.on('error', reject)
worker.postMessage({
measurements,
options,
})
})
})
export.worker.js (same folder as main.ts):
const { parentPort } = require('worker_threads')
const { Export } = require('../preload/export')
parentPort.on('message', async (data) => {
const { measurements, options } = data
await Export.export(measurements, options)
parentPort.close()
})
When I try to run this I get:
Error occurred in handler for 'export': Error: Cannot find module '../preload/export'
Require stack:
- C:\Development\spectro-demo\internal-client\.webpack\main\a3142abb2db60e4fab06.js
at Function.Module._resolveFilename (internal/modules/cjs/loader.js:892:15)
at Function.Module._load (internal/modules/cjs/loader.js:737:27)
at Module.require (internal/modules/cjs/loader.js:964:19)
at require (internal/modules/cjs/helpers.js:88:18)
at Object.<anonymous> (C:\Development\spectro-demo\internal-client\.webpack\main\a3142abb2db60e4fab06.js:2:20)
at Module._compile (internal/modules/cjs/loader.js:1083:30)
at Object.Module._extensions..js (internal/modules/cjs/loader.js:1113:10)
at Module.load (internal/modules/cjs/loader.js:940:32)
at Function.Module._load (internal/modules/cjs/loader.js:781:14)
at Function.executeUserEntryPoint [as runMain] (internal/modules/run_main.js:72:12) {
code: 'MODULE_NOT_FOUND',
requireStack: [
'C:\\Development\\spectro-demo\\internal-client\\.webpack\\main\\a3142abb2db60e4fab06.js'
]
}
So I'm wondering: How can I use worker_threads that reference modules in my project?
I was able to fix it. Seems to be a bug in webpack 5. See this repo for a workaround: https://github.com/DustinJSilk/web-worker-ts-webpack-test

cant send a message to a specific channel

I have a simple dc bot, code goes like this. I tried to simplfy it to make it more readable
const client = new Discord.Client();
...
client.on('ready', () => {
client.channels.cache.get('315445287374028800').send("works here");
});
setInterval(( () =>{
try{
removeHTML(downloadHTML);
} catch(err){
console.log(err);
}
}),30000);
...
...
let removeHTML = function(callback){
client.channels.cache.get('315445287374028800').send("WORKS HERE");
readHTML();
...
}
let readHTML = function(){
console.log("dolar is read");
//client.channels.cache.get('315445287374028800').send("DOESNT WORK HERE");
fs.readFile(dir + '/index.html' , 'utf-8', function(err,html){
if(err)
console.log(err);
else{
//client.channels.cache.get('315445287374028800').send("DOESNT WORK HERE");
if(isPeak){
//client.channels.cache.get('315445287374028800').send("DOESNT WORK HERE");
}
}
});
}
seems like send function doesnt work in callback functions but how can i fix this?
Error type: same error for all ("DOESNT WORK HERE") lines :
TypeError: Cannot read property 'send' of undefined
at readHTML (C:\Users\user\Desktop\Discord Bot\index.js:142:18)
at Object.<anonymous> (C:\Users\user\Desktop\Discord Bot\index.js:182:1)
at Module._compile (internal/modules/cjs/loader.js:1015:30)
at Object.Module._extensions..js (internal/modules/cjs/loader.js:1035:10)
at Module.load (internal/modules/cjs/loader.js:879:32)
at Function.Module._load (internal/modules/cjs/loader.js:724:14)
at Function.executeUserEntryPoint [as runMain]
I have turned all functions to async-await instead and it worked

TypeError: Cannot read property 'showMessageBox' of undefined electron in node js

Below code is just to display the dialog box using electron node module.
app.js
const { dialog } = require('electron')
const response = dialog.showMessageBox(null);
console.log(response);
Need help to understand why I am getting below error message:
const response = dialog.showMessageBox(null);
^
TypeError: Cannot read property 'showMessageBox' of undefined
at Object.<anonymous> (C:\Users\1217688\Desktop\WebApp\node-elect-test\app.js:2:25)
at Module._compile (module.js:660:30)
at Object.Module._extensions..js (module.js:671:10)
at Module.load (module.js:573:32)
at tryModuleLoad (module.js:513:12)
at Function.Module._load (module.js:505:3)
at Function.Module.runMain (module.js:701:10)
at startup (bootstrap_node.js:190:16)
at bootstrap_node.js:662:3
In renderer process, add .remote
const { dialog } = require('electron').remote
Try calling the dialog module when the app is ready:
app.on('ready', () => {
const { dialog } = require('electron')
dialog.showMessageBox(null);
})

Nodejs, Electron nightmare is not defined when it's installed?

I've installed Nightmare via NPM this is my code:
var jquery = require('jquery')
var nightmare = require('nightmare')
var nightmare = Nightmare({ show: true });
$( "#test" ).addEventListener('click',() => {
nightmare
.goto('http://akhiljose.me/master/paste/')
.type('.form-control', 'Test')
.type('input[type=test]', 'nightmare_test')
.click('input[type=submit]')
.wait(7000)
.evaluate(function () {
return document.querySelector('pre').innerText;
})
.end()
.then(function (result) {
console.log(result);
})
.cat(function (error) {
console.error('Search failed:', error);
})});
However console logs:
C:\Users\ninja_000\Desktop\clu-gen\index.js:3 Uncaught ReferenceError: Nightmare is not defined
at Object.<anonymous> (C:\Users\ninja_000\Desktop\clu-gen\index.js:3:17)
at Object.<anonymous> (C:\Users\ninja_000\Desktop\clu-gen\index.js:22:3)
at Module._compile (module.js:642:30)
at Object.Module._extensions..js (module.js:653:10)
at Module.load (module.js:561:32)
at tryModuleLoad (module.js:504:12)
at Function.Module._load (module.js:496:3)
at Module.require (module.js:586:17)
at require (internal/module.js:11:18)
at file:///C:/Users/ninja_000/Desktop/clu-gen/index.html:12:5
I'm very new to nodejs what is causing this error? Am I do something wrong?
You are calling an undefined variable.
var jquery = require('jquery')
var nightmare = require('nightmare')
var nightmare = Nightmare({ show: true });
The second line declares a variable nightmare but the next line you are calling Nightmare. Make the second line uppercase.
var jquery = require('jquery')
var Nightmare = require('nightmare')
var nightmare = Nightmare({ show: true });
You can see from the second line of the stack trace:
at Object.<anonymous> (C:\Users\ninja_000\Desktop\clu-gen\index.js:3:17)
Line 3:17, there is an uncaught ReferenceError: Nightmare. This make sense because Nightmare is not defined, so nodejs cannot find it. The line numbers in the stack trace are useful to pinpoint where in the code the error is occurring. You can also use a linter which will show an error for trying to use an undefined variable. Something like eslint.
Should've defined as Nightmare not nightmare

Replacing karma with jasmine-node for my AngularJS tests?

Jasmine AngularJS test (passes in karma start configs/karma.conf.js)
describe('IndexController', function () {
beforeEach(module('myApp'));
var ctrl, scope;
beforeEach(inject(function ($controller, $rootScope) {
scope = $rootScope.$new();
ctrl = $controller('IndexController', {
$scope: scope
});
}));
it('should add name parameter to scope', function () {
expect(scope.name).toBeDefined();
});
});
Contents of controllers.js
var myApp = angular.module('myApp', []);
myApp.controller('IndexController', function ($scope) {
$scope.name = 'bob';
});
Output of: jasmine-node test/ --junitreport
Message:
TypeError: object is not a function
Stacktrace:
TypeError: object is not a function
at null.<anonymous> (/tmp/tests/test/unit/controllerSpec.js:38:16)
at Object.<anonymous> (/tmp/tests/test/unit/controllerSpec.js:36:1)
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 Module.require (module.js:364:17)
at require (module.js:380:17)
beforeEach() taks in a function. Be sure module('myApp') and inject(...) are returning actual function definitions. Jasmine's beforeEach is like "call the passed function before each test", so you may want:
beforeEach( function(){ module('myApp') } );
I am unfamiliar with karma, but do use jasmine's done() method in my beforeEach() like this:
var valueForEachTest = null;
beforeEach( function(done) {
doSomething( function(value){
valueForEachTest = value;
done();
});
} );
Not using that done() call breaks my tests because I'm doing a few asynchronous call in there (perhaps Jasmine is not waiting for beforeEach to finish?).
Angular is made to run in the browser. It will not run in node. At least, not without a lot of effort.
There has been an attempt to port it to node, but that project is really intended to render angular pages server side for search engine optimization. Unless you have a really good reason, you shouldn't be trying to test Angular apps in Node.

Resources