Access Node module on Electron child process after compiling - node.js

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

Related

TypeError: Cannot read properties of undefined (reading 'getBalance') in node.js

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

Object.writeFileSync - Received type number

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');
}
};

TypeError: Cannot convert object to primitive value in node.js

I am working on node.js.
node.js version is v14.1.0.
KingInfo.js
"use strict";
const db_module = require('../DB/db');
(async function(){
console.log("start");
let sql = [];
sql.push("SELECT count(*) as count");
sql.push(" FROM dbname.tablename");
let result = await db_module.query(sql.join(""));
console.log("result="+Object.entries(result));
console.log("end");
}());
db.js
"use strict";
const mysql = require('mysql');
const connection = mysql.createConnection({
host: 'localhost',
user: 'root',
database: 'databasename'
});
async function query(sql){
console.log("query.1");
await connection.connect((err) => {
console.log("connection.connect");
if (err) throw err;
});
return connection.query(sql, function (err, result, fields) {
console.log("connection.query.1");
if (err) throw err;
return result;
});
}
module.exports = {
query: query
}
I run node KingInfo.js then got the errors and logs:
start
query.1
(node:15792) UnhandledPromiseRejectionWarning: TypeError:
Cannot convert object to primitive value
at Array.join (<anonymous>)
at Array.toString (<anonymous>)
at Array.join (<anonymous>)
at Array.toString (<anonymous>)
at E:\XXXXXX\XXXX\XXXX\XXXX\XXXXXXX\XXXXXXX\XXXXXXX\KingInfo.js:33:24
at processTicksAndRejections (internal/process/task_queues.js:97:5)
(Use `node --trace-warnings ...` to show where the warning was created)
(node:15792) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). To terminate the node process on unhandled promise rejection, use the CLI flag `--unhandled-rejections=strict` (see https://nodejs.org/api/cli.html#cli_unhandled_rejections_mode). (rejection id: 1)
(node:15792) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.
connection.connect
connection.query.1
it seems stopped at this code: let result = await db_module.query(sql.join("")); because it doesn't have log for the code: console.log("result="+Object.entries(result)); and the rest.
I am new to async process, promis, await/async things. So my code related to async might cause this errer?
I should have asked in another post but I am not confident the code in the db module, either. If you have some advice for me how to fix it properly, please tell me.
This question was asked 8 month ago, but I will provide some advise for people who face such a problem. Well,
mysql library is callback-based-only, it's methods not return promises, if you need promises, then consider something like promise-mysql.
If you look at your output, you will see that after unhandledRejection error there are 2 lines printed, which are the console.log's from your connect and query callbacks, so, in the end, your query is performed successfully.
The thing with this error is that, object that is returned by connection.query call, contains some property, that can not be converted to primitive value, due to either being torn from the simple object prototype chain(i.e. something like ({}).__proto__ = null), or there are invalid overrides of Symbol.toPrimitive method or both of toString and valueOf methods.
Here is an example code with same error result:
const o = {}
o.toString = undefined
o.valueOf = () => ({}) // Must return primitive
const returnedByQuery = { o }
console.log("result " + Object.entries(returnedByQuery))
And here is the same result as you have:
/home/xxx/index.js:7
console.log("result " + Object.entries(returnedByQuery))
^
TypeError: Cannot convert object to primitive value
at Array.join (<anonymous>)
at Array.toString (<anonymous>)
at Array.join (<anonymous>)
at Array.toString (<anonymous>)
at Object.<anonymous> (/home/xxx/index.js:7:23)
at Module._compile (internal/modules/cjs/loader.js:1063:30)
at Object.Module._extensions..js (internal/modules/cjs/loader.js:1092:10)
at Module.load (internal/modules/cjs/loader.js:928:32)
at Function.Module._load (internal/modules/cjs/loader.js:769:14)
at Function.executeUserEntryPoint [as runMain] (internal/modules/run_main.js:72:12)
When you performing concatenation, it will try to convert each entry - [key, value] tuple to string, for this it will try to convert given value to string, and here it will fail.
And finally, if you need to get promises from callback based methods:
const p = new Promise(
(res, rej) => connection.query(sql,
(err, result) => {
if (err) return rej(err)
return res(result)
}
)
)
// then you can await it(In async functions)
await p

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);
})

Node.js, Express.js - unexpected token {

My app crashes every time it reaches this line:
const {name, price} = req.query;
^
can't seem to locate the exact answer..here is the error log
SyntaxError: Unexpected token {
at exports.runInThisContext (vm.js:53:16)
at Module._compile (module.js:373:25)
at Object.Module._extensions..js (module.js:416:10)
at Module.load (module.js:343:32)
at Function.Module._load (module.js:300:12)
at Function.Module.runMain (module.js:441:10)
at startup (node.js:140:18)
at node.js:1043:3
context:
app.get('/products/add' , (req, res) => {
const {name, price} = req.query;
const INSERT_PRODUCTS_QUERY = `INSERT INTO products (name, price) VALUES ('${ name }', ${ price })`;
connection.query(INSERT_PRODUCTS_QUERY, (err,results) => {
if(err)
{
return res.send(err);
}
else
{
return res.send('succesfully added product');
}
});
});
According to node.green, the object destructuring with primitives syntax works after Node.JS v6.4.0, and throws the Unexpected Token { on Node.js versions below that.
Also, the object rest/spread properties only works out of the box from Node v8.6.0. It works in v8.2.1 with the --harmony flag, and throws the Unexpected Token ... on Node.js versions below that.
You tried to use destructuring assignment. AFAIK its support by nodejs v.6+ from a box and from 4.2.2 with flag --harmony_destructuring

Resources