I have old monolith app written in NodeJS.
It requires lots of node_modules.
Application is exiting, because of unhandled exception which is happening in some of the modules.
You have triggered an unhandledRejection, you may have forgotten to catch a Promise rejection: undefined
TypeError [ERR_INVALID_ARG_TYPE]: The "data" argument must be of type string or an instance of Buffer, TypedArray, or DataView. Received type number (22388)
at Object.writeFileSync (node:fs:2146:5)
at ProcessContainer (/usr/lib/node_modules/pm2/lib/ProcessContainer.js:67:8)
at Object.<anonymous> (/usr/lib/node_modules/pm2/lib/ProcessContainer.js:100:3)
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:79:12)
at node:internal/main/run_main_module:17:47
For now I have included this code in hope that it will give me stack trace:
process.on('uncaughtException', (e) => {
logger.error(e.stack || e, `uncaughtException happened`);
process.exit(1);
});
Problem is it takes several days/weeks for error to occur.
Did anyone had similar/same issue?
Is there a way to globally override function of some module?
If this is possible it would be easy for me to create a wrapped function with try catch.
I use NodeJS 14, 16 has same issue. I can't rollaback node version
I will try with this. However I am unsure if it overrided fs.writeFileSync everywhere
import fs from 'fs';
const f = fs.writeFileSync;
delete fs.writeFileSync;
fs.writeFileSync = (fileName, data, options) => {
try {
logger.debug({ fileName }, `Overriding writeFileSync function`);
f(fileName, data, options);
} catch (err) {
logger.error({ err: err.stack || err, fileName }, 'Error in writing file');
}
};
Related
I am getting error when using web3.js to get the balance of an account. I am using ganache. My code is below,
var Web3 = require("web3");
//connect with ganache
const ganacheWeb3 = new Web3(
new Web3.providers.HttpProvider("HTTP://127.0.0.1:7545")
);
console.log(ganacheWeb3);
//check the balance of an account
const balanceOfAccount = Web3.Eth.getBalance(
"0xaEA4e665291fdBFe4bAFc5b81F6F213551180ab5"
);
console.log(
balanceOfAccount.then((result) =>
console.log(Web3.utils.fromWei(result, "ether"))
)
);
Web3.eth.getBalance(
"0xaEA4e665291fdBFe4bAFc5b81F6F213551180ab5",
(error, result) => {
if (error) {
console.log(error);
} else {
console.log(result);
}
}
);
I have used the normal functional way and callback way. I don't know which one is correct. But still I am getting error. The error is,
const balanceOfAccount = Web3.Eth.getBalance(
^
TypeError: Cannot read properties of undefined (reading 'getBalance')
at Object.<anonymous> (D:\Blockchain Development\Web3.js\intro-to-web3.js\index.js:10:35)
at Module._compile (node:internal/modules/cjs/loader:1159:14)
at Module._extensions..js (node:internal/modules/cjs/loader:1213:10)
at Module.load (node:internal/modules/cjs/loader:1037:32)
at Module._load (node:internal/modules/cjs/loader:878:12)
at Function.executeUserEntryPoint [as runMain] (node:internal/modules/run_main:82:12)
at node:internal/main/run_main_module:23:47
I am trying to get the value of an ethereum account. But getting an error.
Change Web3.Eth.getBalance(...) to Web3.eth.getBalance(...).
Documentation: https://web3js.readthedocs.io/en/v1.2.11/web3-eth.html#getbalance
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
I am making an App with electron and in the main process, i make an xml parser using child process with the following code:
xmlparser.js
const {parseString} = require('xml2js')
const moment = require('moment')
const testStrangeLayer = new RegExp(/^\de-\d$/)
const parseXML = function(str) {
try {
parseString(
//parse function goes here
)
} catch(e) {
process.exit(3)
}
}
process.on('message',parseXML)
and it is consumed with this:
consumer.js
const fork = require('child_process').fork
const proc = fork('xmlparser.js')
let result
proc.on('message',function(m){
result = m
console.log('parse successful')
proc.kill()
})
proc.on('exit',function(code,signal){
if(code) {
console.error('parsing error')
} else {
console.log(result)
}
})
proc.send(data)
When i am on development stage, this works just fine. The problem comes after i compile the app. And here's the error i found:
Error: Cannot find module 'xml2js'
at Function.Module._resolveFilename (module.js:543:15)
at Function.Module._load (module.js:473:25)
at Module.require (module.js:586:17)
at require (internal/module.js:11:18)
at Object.<anonymous> (C:\<Path to App Folder>\resources\other-scripts\app\xmlp
arser.js:1:178)
at Object.<anonymous> (C:\<Path to App Folder>\resources\other-scripts\app\xmlp
arser.js:53: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)
parsing error
(node:10888) UnhandledPromiseRejectionWarning: Unhandled promise rejection (rejection id: 1): #<Object>
(node:10888) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejection
s that are not handled will terminate the Node.js process with a non-zero exit code.
module.js:545
throw err;
^
I wonder what went wrong, i even already add 'child_process' to the project's dependency list. And my aim is to distribute this app without client installing nodejs on their machine.
Thanks for your helps
I add 'error' event Listener to watcher returned from fs.watch().
But error event handler does not trigger when I watch a file which is not existed.
const filename = 'test/target.txt';
const filenameNotExist = 'test/not-exist-target.txt';
console.log('Now watching the target.txt for changes...');
const watcher = fs.watch(filenameNotExist || filename);
watcher.on('change', (eventType, fname) => {
switch (eventType) {
case 'rename':
console.log(`file ${fname} renamed`);
break;
case 'change':
console.log(`file ${fname} changed`);
break;
default:
break;
}
});
// error event handler does not trigger.
watcher.on('error', err => {
console.log('filename is not correct');
if (err) throw err;
});
stdout give me this output:
Now watching the target.txt for changes...
fs.js:1384
throw error;
^
Error: watch test/not-exist-target.txt ENOENT
at _errnoException (util.js:1041:11)
at FSWatcher.start (fs.js:1382:19)
at Object.fs.watch (fs.js:1408:11)
at Object.<anonymous> (/Users/elsa/workspace/Training.nodejs/examples/api/fs/watcher.js:10:20)
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)
There is no filename is not correct log.
which case will trigger watcher error event handler?
The fs.FSWatcher docs says that it is returned on a successful fs.watch() call. Check the returned object, maybe it is an Error (ENOENT) and not an FSWatcher you expect.
(Actually I believe an ENOENT is thrown, so your watcher.on(...) calls are never executed. You can use a try-catch to make sure.)
var kafka = require('kafka-node');
Producer = kafka.Producer;
KeyedMessage = kafka.KeyedMessage;
client = new kafka.Client();
producer = new Producer(client);
km = new KeyedMessage('key', 'message');
payloads = [
{ topic: 'topic1', messages: 'hi', partition: 0 },
{ topic: 'topic2', messages: ['hello', 'world', km] }
];
producer.on('ready', function ()
{
producer.send(payloads, function (err, data)
{
console.log(data);
});
});
producer.on('error', function (err) {});
//error for that code
baaz#bit:~$ node kafka1.js
/home/baaz/node_modules/kafka-node/lib/codec/snappy.js:18
var SNAPPY_MAGIC = Buffer.from(SNAPPY_MAGIC_BYTES).toString('hex');
^
TypeError: this is not a typed array.
at Function.from (native)
at Object.<anonymous> (/home/baaz/node_modules/kafka-node/lib/codec/snappy.js:18:29)
at Module._compile (module.js:425:26)
at Object.Module._extensions..js (module.js:432:10)
at Module.load (module.js:356:32)
at Function.Module._load (module.js:311:12)
at Module.require (module.js:366:17)
at require (module.js:385:17)
at Object.<anonymous> (/home/baaz/node_modules/kafka-node/lib/codec/index.js:4:19)
at Module._compile (module.js:425:26)
Short Answer :
Either increase the node version above 4.5 or
use "kafka-node": "1.6.2" or lesser
Long Answer
with node 4.5 and above, node deprecated the old way of creating buffer via a constructor, so all node js version below 4.5 do not have new that support. and kafka-node version > 1.6.2 uses the buffer.from to create the buffer so we have the compatibility issues.
Cheers
Happy coding