Why is it saying the property of show is undefined? - node.js

I am trying to make a nodecg bundle similar to:https://github.com/Chr12t0pher/vespyr-nodecg
I currently have it hosted here: https://github.com/SilverStateEsports/lolStream
Im not quite sure what the problem is and while googleing part of the stack trace, it came up with broser support being deprecated, but that did not seem to be the problem.
code:
var concat = require("concat-stream");
var hyperquest = require('hyperquest');
var querystring = require('querystring');
var URL = 'http://strawpoll.me/api/v2/polls';
var HEADERS = {
'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8',
'X-Requested-With': 'node-strawpoll'
};
function create(options) {
var stream = hyperquest.post(URL, {headers: HEADERS});
stream.end(querystring.stringify(options));
return stream;
}
function get(id) {
var stream = hyperquest.get(URL + '/' + id);
return stream;
}
module.exports = function(nodecg) {
var strawpollReplicant = nodecg.Replicant("strawpoll",
{defaultValue: {"id": "", "options": ["", ""], "result": [0,0], "show": false, "time": 0}}
);
nodecg.listenFor("strawpoll-create", function(data) {
var stream = create({
title: "Who will win?",
options: data,
multi: false,
permissive: true
});
stream.pipe(concat(function(poll) {
poll = JSON.parse(poll);
strawpollReplicant.value = {"id": poll.id, "options": data, "result": [0, 0], "show": false, "time": 0};
}));
});
strawpollReplicant.on("change", function(oldVal, newVal) {
if (newVal["show"]) {
if (newVal["time"] <= 600) { // Update for 10 minutes max.
var stream = get(newVal["id"])
.pipe(concat(function(poll) {
poll = JSON.parse(poll);
setTimeout(function() {
newVal["time"] += 3;
newVal["result"] = poll["votes"];
strawpollReplicant.value = newVal;
}, 3000);
}));
}
}
});
};
Stack trace:
warn: [nodecg/lib/server/extensions] Failed to mount sse-lol-stream extension:
TypeError: Cannot read property 'show' of undefined
at C:\Users\Ethan\Desktop\lolStream\nodecg\bundles\sse-lol-stream\extension\strawpoll.js:42:13
at Replicant.<anonymous> (C:\Users\Ethan\Desktop\lolStream\nodecg\lib\replicant\replicant.js:167:5)
at Replicant.emit (events.js:310:20)
at Replicant.EventEmitter.emit (domain.js:482:12)
at _addListener (events.js:353:14)
at Replicant.addListener (events.js:401:10)
at module.exports (C:\Users\Ethan\Desktop\lolStream\nodecg\bundles\sse-lol-stream\extension\strawpoll.js:41:24)
at module.exports (C:\Users\Ethan\Desktop\lolStream\nodecg\bundles\sse-lol-stream\extension\index.js:5:30)
at _loadExtension (C:\Users\Ethan\Desktop\lolStream\nodecg\lib\server\extensions.js:103:37)
at EventEmitter.module.exports.init (C:\Users\Ethan\Desktop\lolStream\nodecg\lib\server\extensions.js:32:6)
at EventEmitter.module.exports.start (C:\Users\Ethan\Desktop\lolStream\nodecg\lib\server\index.js:310:19)
at Object.<anonymous> (C:\Users\Ethan\Desktop\lolStream\nodecg\index.js:77:8)
at Module._compile (internal/modules/cjs/loader.js:1156:30)
at Object.Module._extensions..js (internal/modules/cjs/loader.js:1176:10)
at Module.load (internal/modules/cjs/loader.js:1000:32)
at Function.Module._load (internal/modules/cjs/loader.js:899:14)
at Module.require (internal/modules/cjs/loader.js:1042:19)
at require (internal/modules/cjs/helpers.js:77:18)
at Command.<anonymous> (C:\Users\Ethan\AppData\Roaming\npm\node_modules\nodecg-cli\dist\commands\start.js:11:13)
at Command.listener (C:\Users\Ethan\AppData\Roaming\npm\node_modules\nodecg-cli\node_modules\commander\index.js:315:8)
at Command.emit (events.js:310:20)
at Command.parseArgs (C:\Users\Ethan\AppData\Roaming\npm\node_modules\nodecg-cli\node_modules\commander\index.js:651:12)
at Command.parse (C:\Users\Ethan\AppData\Roaming\npm\node_modules\nodecg-cli\node_modules\commander\index.js:474:21) at Object.<anonymous> (C:\Users\Ethan\AppData\Roaming\npm\node_modules\nodecg-cli\dist\index.js:37:9)
at Module._compile (internal/modules/cjs/loader.js:1156:30)
at Object.Module._extensions..js (internal/modules/cjs/loader.js:1176:10)
at Module.load (internal/modules/cjs/loader.js:1000:32)
at Function.Module._load (internal/modules/cjs/loader.js:899:14)
at Module.require (internal/modules/cjs/loader.js:1042:19)
at require (internal/modules/cjs/helpers.js:77:18)
at Object.<anonymous> (C:\Users\Ethan\AppData\Roaming\npm\node_modules\nodecg-cli\dist\bin\nodecg.js:22:1)
at Module._compile (internal/modules/cjs/loader.js:1156:30)
at Object.Module._extensions..js (internal/modules/cjs/loader.js:1176:10)
at Module.load (internal/modules/cjs/loader.js:1000:32)
at Function.Module._load (internal/modules/cjs/loader.js:899:14)
at Function.executeUserEntryPoint [as runMain] (internal/modules/run_main.js:74:12)
at internal/main/run_main_module.js:18:47

I'm guessing you're getting a change event where newVal is undefined:
strawpollReplicant.on("change", function(oldVal, newVal) {
if (newVal["show"]) {
I'd make sure that newVal is actually defined. I haven't used nodecg so I don't have further ideas.

Related

importing mongodb results in error that is not related to mongodb when running the script using node command

I have a stand alone script that I am using to create an admin user. There will always be only one admin user. However, when I run the standalone script using node command in my nextjs project, I get this weird error below
node indexUser.js
/Users/nabeel.77.dev/Documents/portfolio/node_modules/whatwg-url/lib/utils.js:50
var AsyncIteratorPrototype = Object.getPrototypeOf(Object.getPrototypeOf( /*#__PURE__*/_wrapAsyncGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee() {
^
TypeError: Cannot convert undefined or null to object
at Function.getPrototypeOf (<anonymous>)
at Object.<anonymous> (/Users/nabeel.77.dev/Documents/portfolio/node_modules/whatwg-url/lib/utils.js:34:39)
at Module._compile (node:internal/modules/cjs/loader:1218:14)
at Module._compile (/Users/nabeel.77.dev/Documents/portfolio/node_modules/pirates/lib/index.js:136:24)
at Module._extensions..js (node:internal/modules/cjs/loader:1272:10)
at Object.newLoader [as .js] (/Users/nabeel.77.dev/Documents/portfolio/node_modules/pirates/lib/index.js:141:7)
at Module.load (node:internal/modules/cjs/loader:1081:32)
at Function.Module._load (node:internal/modules/cjs/loader:922:12)
at Module.require (node:internal/modules/cjs/loader:1105:19)
at require (node:internal/modules/cjs/helpers:103:18)
at Object.<anonymous> (/Users/nabeel.77.dev/Documents/portfolio/node_modules/whatwg-url/lib/URL.js:4:15)
at Module._compile (node:internal/modules/cjs/loader:1218:14)
at Module._compile (/Users/nabeel.77.dev/Documents/portfolio/node_modules/pirates/lib/index.js:136:24)
at Module._extensions..js (node:internal/modules/cjs/loader:1272:10)
at Object.newLoader [as .js] (/Users/nabeel.77.dev/Documents/portfolio/node_modules/pirates/lib/index.js:141:7)
at Module.load (node:internal/modules/cjs/loader:1081:32)
at Function.Module._load (node:internal/modules/cjs/loader:922:12)
at Module.require (node:internal/modules/cjs/loader:1105:19)
at require (node:internal/modules/cjs/helpers:103:18)
at Object.<anonymous> (/Users/nabeel.77.dev/Documents/portfolio/node_modules/whatwg-url/webidl2js-wrapper.js:3:13)
at Module._compile (node:internal/modules/cjs/loader:1218:14)
at Module._compile (/Users/nabeel.77.dev/Documents/portfolio/node_modules/pirates/lib/index.js:136:24)
at Module._extensions..js (node:internal/modules/cjs/loader:1272:10)
at Object.newLoader [as .js] (/Users/nabeel.77.dev/Documents/portfolio/node_modules/pirates/lib/index.js:141:7)
at Module.load (node:internal/modules/cjs/loader:1081:32)
at Function.Module._load (node:internal/modules/cjs/loader:922:12)
at Module.require (node:internal/modules/cjs/loader:1105:19)
at require (node:internal/modules/cjs/helpers:103:18)
at Object.<anonymous> (/Users/nabeel.77.dev/Documents/portfolio/node_modules/whatwg-url/index.js:3:34)
at Module._compile (node:internal/modules/cjs/loader:1218:14)
at Module._compile (/Users/nabeel.77.dev/Documents/portfolio/node_modules/pirates/lib/index.js:136:24)
at Module._extensions..js (node:internal/modules/cjs/loader:1272:10)
at Object.newLoader [as .js] (/Users/nabeel.77.dev/Documents/portfolio/node_modules/pirates/lib/index.js:141:7)
at Module.load (node:internal/modules/cjs/loader:1081:32)
at Function.Module._load (node:internal/modules/cjs/loader:922:12)
at Module.require (node:internal/modules/cjs/loader:1105:19)
at require (node:internal/modules/cjs/helpers:103:18)
at Object.<anonymous> (../src/index.ts:1:1)
at Module._compile (node:internal/modules/cjs/loader:1218:14)
at Module._compile (/Users/nabeel.77.dev/Documents/portfolio/node_modules/pirates/lib/index.js:136:24)
at Module._extensions..js (node:internal/modules/cjs/loader:1272:10)
at Object.newLoader [as .js] (/Users/nabeel.77.dev/Documents/portfolio/node_modules/pirates/lib/index.js:141:7)
at Module.load (node:internal/modules/cjs/loader:1081:32)
at Function.Module._load (node:internal/modules/cjs/loader:922:12)
at Module.require (node:internal/modules/cjs/loader:1105:19)
at require (node:internal/modules/cjs/helpers:103:18)
at Object.<anonymous> (../src/connection_string.ts:3:1)
at Module._compile (node:internal/modules/cjs/loader:1218:14)
at Module._compile (/Users/nabeel.77.dev/Documents/portfolio/node_modules/pirates/lib/index.js:136:24)
at Module._extensions..js (node:internal/modules/cjs/loader:1272:10)
Node.js v19.3.0
The script I am running has the below code:
import bcrypt from 'bcryptjs';
import MongoClientConnection from '../db';
import readline from 'readline';
import { logger } from '../logger';
const rl = readline.createInterface({
input: process.stdin,
output: process.stdout,
});
rl.question('Enter username: ', (username) => {
rl.question('Enter email: ', (email) => {
rl.question('Enter password: ', async (password) => {
const hashedPassword = await bcrypt.hash(password, 10);
const adminUserData = { username, email, hashedPassword };
try {
const db = await MongoClientConnection.Get();
const res = await db.insert(adminUserData);
} catch (e) {
logger.error(e);
}
rl.close();
});
});
});
In the code above, when I remove import MongoClientConnection from '../db'; the script works fine so, I believe the error is because of mongodb. I am using singleton connection for mongodb and have the below code for that
import { MongoClient } from 'mongodb';
const MongoClientConnection = (() => {
let db = null;
let instance = 0;
const DbConnect = async () => {
try {
let url = process.env.DB_URL;
let mongoClient = await MongoClient.connect(url, {
useUnifiedTopology: true,
});
const mongoDbInstance = mongoClient.db(process.env.DB);
return mongoDbInstance;
} catch (e) {
return e;
}
};
const Get = async () => {
try {
instance++; // this is just to count how many times our singleton is called.
console.log(`DbConnection called ${instance} times`);
if (db != null) {
console.log(`db connection is already alive`);
return db;
} else {
console.log(`getting new db connection`);
db = await DbConnect();
return db;
}
} catch (e) {
return e;
}
};
return {
Get: Get,
};
})();
export default MongoClientConnection;
Cannot really find any solution to this.

JS- why is context not passed in to child function?

I am trying to declare a logger object, then have a child function write to the log that was declared in the parent using the context. However the context appears to be undefined inside the children, whether I use an arrow function or not.
Is it possible to pass the winston object to the child function implicitly ie without having to pass a winston object as a parameter?
Error log output:
this main context: {}
undefined
l1 err: TypeError: Cannot read properties of undefined (reading 'winston')
at l1 (MYPATH\cw_log_test_helper.ts:4:19)
at run (MYPATH\cw_log_contexts.ts:30:7)
at Object.<anonymous> (MYPATH\cw_log_contexts.ts:39:1)
at Module._compile (node:internal/modules/cjs/loader:1101:14)
at Module.m._compile (MYPATH\node_modules\ts-node\src\index.ts:1371:23)
at Module._extensions..js (node:internal/modules/cjs/loader:1153:10)
at Object.require.extensions.<computed> [as .ts] (MYPATH\node_modules\ts-node\src\index.ts:1374:12)
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)
{ l1: [Function: l1], r1: [AsyncFunction: r1] }
r1 err: TypeError: Cannot read properties of undefined (reading 'error')
at r1 (MYPATH\cw_log_test_helper.ts:12:31)
at run (MYPATH\cw_log_contexts.ts:31:7)
at Object.<anonymous> (MYPATH\cw_log_contexts.ts:39:1)
at Module._compile (node:internal/modules/cjs/loader:1101:14)
at Module.m._compile (MYPATH\node_modules\ts-node\src\index.ts:1371:23)
at Module._extensions..js (node:internal/modules/cjs/loader:1153:10)
at Object.require.extensions.<computed> [as .ts] (MYPATH\node_modules\ts-node\src\index.ts:1374:12)
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)
bye
main.ts
var winston=require('winston');
var WinstonCloudWatch=require('winston-cloudwatch');
import { l1, r1 } from './cw_log_test_helper';
const AWS = require('aws-sdk');
AWS.config.update({
region: 'us-east-1',
});
var run=()=>{
let sname=`mylambda`
var self=winston.add(new WinstonCloudWatch({
name:sname,
cloudWatchLogs: new AWS.CloudWatchLogs(),
logGroupName: 'winston-testing',
logStreamName: sname
}));
console.log(`this main context:`,this)
winston.error('first'); //<<<<<<<<<<<<<<<<<<WORKS
l1(`hello`) //<<<<<<<<<<<<<<<<FAILS
r1('hi') //<<<<<<<<<<<<<<<<FAILS
// flushes the logs and clears setInterval
var transport = self.transports.find((t) => t.name === sname)
transport.kthxbye(function() {
console.log('bye');
});
}
run()
cw_log_test_helper.ts:
export var l1=function(ltxt:string){
console.log(this)
try{
(this as any).winston.error(ltxt);
}catch(e){
console.log(`l1 err:`,e)
}
}
export var r1 = async (ltxt:string) => {
console.log(this)
try{
(this as any).winston.error(ltxt);
}catch(e){
console.log(`r1 err:`,e)
}
}

Extending String prototype. Cannot both specifiy accessors and a value or writable attribute

I am creating this custom method inside Object, Array, and String. When I run it on the Azure function app it works, no issue there, but when I start to test it using Mocha/Chai. It gives me below error:
TypeError: Invalid property descriptor. Cannot both specify accessors and a value or writable attribute, #<Object>
Here is my code,
// declare global{
interface String {
contains(s: string): boolean;
}
interface Object {
contains(s: string) : boolean;
}
// }
// String
String.prototype.contains = function (s: string) : boolean {
return String(this).includes(s);
};
// Object
Object.prototype.contains = function (s: string): boolean {
return Object(this).hasOwnProperty(s);
}
//export {};
I import it into my function.
Note: This function works well in live/local on its own.
import 'custom/prototype/file';
export const myFunction : Function = (s: string) : Object => {
const bool : boolean = s.contains('look for this string');
const obj = { name: "string" };
const fbool : boolean = obj.contains('name');
return {
foo: s
fboo: fbool
};
}
Now in my test.spec.ts file I ran a test using the myFunction above.
I do not understand why it's giving me this error when it has no issues running by itself.
import { myFunction } from 'index/file';
import 'custom/prototype/file';
describe.skip('test case', () => {
it('test',() => {
const object = myFunction('this is a random string');
});
});
Here is the full error log:
TypeError: Invalid property descriptor. Cannot both specify accessors and a value or writable attribute, #<Object>
at Function.defineProperty (<anonymous>)
at Object.<anonymous> (D:\test1\test\test azure\utils\defaultContext.ts:2:8)
at Module._compile (internal/modules/cjs/loader.js:1137:30)
at Module.m._compile (D:\test1\test\test azure\node_modules\ts-node\src\index.ts:439:23)
at Module._extensions..js (internal/modules/cjs/loader.js:1157:10)
at Object.require.extensions.<computed> [as .ts] (D:\test1\test\test azure\node_modules\ts-node\src\index.ts:442:12)
at Module.load (internal/modules/cjs/loader.js:985:32)
at Function.Module._load (internal/modules/cjs/loader.js:878:14)
at Module.require (internal/modules/cjs/loader.js:1025:19)
at require (internal/modules/cjs/helpers.js:72:18)
at Object.<anonymous> (D:\test1\test\test azure\tests\DV_Musculoskeletal.spec.ts:3:1)
at Module._compile (internal/modules/cjs/loader.js:1137:30)
at Module.m._compile (D:\test1\test\test azure\node_modules\ts-node\src\index.ts:439:23)
at Module._extensions..js (internal/modules/cjs/loader.js:1157:10)
at Object.require.extensions.<computed> [as .ts] (D:\test1\test\test azure\node_modules\ts-node\src\index.ts:442:12)
at Module.load (internal/modules/cjs/loader.js:985:32)
at Function.Module._load (internal/modules/cjs/loader.js:878:14)
at Module.require (internal/modules/cjs/loader.js:1025:19)
at require (internal/modules/cjs/helpers.js:72:18)
at Object.implementationOfRequireOrImportForUnstableEsm [as requireOrImport] (D:\test1\test\test azure\node_modules\mocha\lib\esm-utils.js:101:12)
at Object.exports.loadFilesAsync (D:\test1\test\test azure\node_modules\mocha\lib\esm-utils.js:88:34)
at Mocha.loadFilesAsync (D:\test1\test\test azure\node_modules\mocha\lib\mocha.js:467:19)
at singleRun (D:\test1\test\test azure\node_modules\mocha\lib\cli\run-helpers.js:125:15)
at exports.runMocha (D:\test1\test\test azure\node_modules\mocha\lib\cli\run-helpers.js:190:10)
at Object.exports.handler (D:\test1\test\test azure\node_modules\mocha\lib\cli\run.js:366:11)
at D:\test1\test\test azure\node_modules\yargs\build\index.cjs:443:71

Blinking led light using nodejs

I am performing my first IOT project hello world blinking I'm trying to started with web of things book and having a problem.
The book is this: https://webofthings.org/2016/10/23/node-gpio-and-the-raspberry-pi/.
But When I trying to run the code I get the error.
/home/pi/Desktop/hello_world/node_modules/onoff/onoff.js:9 const HIGH_BUF = Buffer.from('1');
TypeError: this is not a typed array.
at Function.from (native)
at Object.<anonymous>
(/home/pi/Desktop/faizan/node_modules/onoff/onoff.js:9:25)
at Module._compile (module.js:409:26)
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 Module.require (module.js:353:17)
at require (internal/module.js:12:17)
at Object.<anonymous> (/home/pi/Desktop/faizan/app.js:1:75)
at Module._compile (module.js:409:26)
The code I'm running is
var onoff = require('onoff');
var Gpio = onoff.Gpio,
led = new Gpio(4,'out'),
interval;
interval = setInterval(function (){
var value = (led.readSync() + 1) % 2;
led.write(value, function() {
console.log("Changed LED state to: " + value);
});
}, 2000);
process.on('SIGINT', function () {
clearInterval(interval);
led.writeSync(0);
led.unexport();
console.log('Bye, bye!');
process.exit();
});

TypeError: Object #<Object> has no method 'Request' with elastic.js

i tried the following sample code:
var es=require("elasticsearch");
var ejs = require("ejs");
var client = new es.Client({
host: 'localhost:9200',
log: 'trace'
});
client.ping({
requestTimeout: 3000,
// undocumented params are appended to the query string
hello: "elasticsearch"
}, function (error) {
if (error) {
console.error('elasticsearch cluster is down!');
} else {
console.log('All is well');
}
});
client.search({
index: 'message-1',
type: 'message',
body: ejs.Request().query(ejs.MatchAllQuery())
}).then(function (resp) {
var hits = resp.hits.hits;
}, function (err) {
console.trace(err.message);
});
i am getting the following error when i try to run: node metric.js
/home/karunakar/test/metricagg/metric.js:27
body: ejs.Request().query(ejs.MatchAllQuery())
^
TypeError: Object #<Object> has no method 'Request'
at Object.<anonymous> (/home/karunakar/test/metricagg/metric.js:27:13)
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:929:3
i could not locate the problem.
-- Thanks
You want the elastic.js module and not ejs, which is a templating engine module.
You can keep the first require("elasticsearch") but the second one should be require("elastic.js") instead of require("ejs")

Resources