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)
}
}
Related
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.
test codeļ¼
function throw_erorr(){
throw TypeError("test error")
}
try{
throw_erorr()
}catch(err){
console.log("==err:", err)
}
results:
PS E:\code\nodejs\star> node .\main.js
==err: TypeError: test error
at throw_erorr (E:\code\nodejs\star\main.js:12:11)
at Object. (E:\code\nodejs\star\main.js:16:5)
at Module._compile (node:internal/modules/cjs/loader:1126:14)
at Object.Module._extensions..js (node:internal/modules/cjs/loader:1180:10)
at Module.load (node:internal/modules/cjs/loader:1004:32)
at Function.Module._load (node:internal/modules/cjs/loader:839:12)
at Function.executeUserEntryPoint [as runMain] (node:internal/modules/run_main:81:12)
at node:internal/main/run_main_module:17:47
Why?Tanks!
In Node.js, I noticed that file operations were not always stable. I have the impression that fs gives up when the operations are not completely finished. Here is an example to illustrate:
"use strict";
Error.stackTraceLimit = Infinity;
const fs = require("fs");
const filename = "foo.txt";
for (let i = 0; ; i++) {
try {
fs.writeFileSync(filename, "bar");
fs.unlinkSync(filename);
}
catch (e) {
throw Object.assign(new Error(`Error at iteration ${i}!`), { cause: e });
}
}
After a certain number of iterations, I get an error :
Error: Error at iteration 12980!
at Object.<anonymous> (C:\test.js:15:4)
at Module._compile (internal/modules/cjs/loader.js:999:30)
at Object.Module._extensions..js (internal/modules/cjs/loader.js:1027:10)
at Module.load (internal/modules/cjs/loader.js:863:32)
at Function.Module._load (internal/modules/cjs/loader.js:708:14)
at Function.executeUserEntryPoint [as runMain] (internal/modules/run_main.js:60:12)
at internal/main/run_main_module.js:17:47 {
cause: Error: EPERM: operation not permitted, open 'foo.txt'
at Object.openSync (fs.js:462:3)
at Object.writeFileSync (fs.js:1384:35)
at Object.<anonymous> (C:\test.js:10:6)
at Module._compile (internal/modules/cjs/loader.js:999:30)
at Object.Module._extensions..js (internal/modules/cjs/loader.js:1027:10)
at Module.load (internal/modules/cjs/loader.js:863:32)
at Function.Module._load (internal/modules/cjs/loader.js:708:14)
at Function.executeUserEntryPoint [as runMain] (internal/modules/run_main.js:60:12)
at internal/main/run_main_module.js:17:47 {
errno: -4048,
syscall: 'open',
code: 'EPERM',
path: 'foo.txt'
}
}
Do you have the same observation?
How can we ensure that these operations are stable?
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
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.