nodejs / help

:sparkles: Need help with Node.js? File an Issue here. :rocket:
1.46k stars 279 forks source link

failing to deploy - TypeError cannot read property of '_events' of undefined #3520

Open twigs67 opened 3 years ago

twigs67 commented 3 years ago

Version

14.4.0

Platform

linux

Subsystem

No response

What steps will reproduce the bug?

Hello,

Apologies if this isn't the correct place for this, but I'm completely lost as to why I'm getting this error. events=target._events does not exist anywhere in my codebase, so i'm guessing it is due to a node_module, but I can't find the culprit.

What's worse is I can't reproduce this locally, it just fails when deploying to our dev environment.

2021-08-29T14:26:05.489-04:00   Running Node Cluster

2021-08-29T14:26:05.489-04:00   Master server started on 1

2021-08-29T14:26:05.529-04:00   events.js:350

2021-08-29T14:26:05.530-04:00   events = target._events;

2021-08-29T14:26:05.530-04:00   ^

2021-08-29T14:26:05.530-04:00   TypeError: Cannot read property '_events' of undefined

2021-08-29T14:26:05.530-04:00   at _addListener (events.js:350:19)

2021-08-29T14:26:05.530-04:00   at addListener (events.js:406:10)

2021-08-29T14:26:05.530-04:00   at Function.clusterize (/usr/src/app/dist/src/core/node-cluster.js:40:30)

2021-08-29T14:26:05.530-04:00   at Object.<anonymous> (/usr/src/app/dist/src/main.js:121:38)

2021-08-29T14:26:05.530-04:00   at Module._compile (internal/modules/cjs/loader.js:1200:30)

2021-08-29T14:26:05.530-04:00   at Object.Module._extensions..js (internal/modules/cjs/loader.js:1220:10)

2021-08-29T14:26:05.530-04:00   at Module.load (internal/modules/cjs/loader.js:1049:32)

2021-08-29T14:26:05.530-04:00   at Function.Module._load (internal/modules/cjs/loader.js:937:14)

2021-08-29T14:26:05.530-04:00   at Function.executeUserEntryPoint [as runMain] (internal/modules/run_main.js:71:12)

2021-08-29T14:26:05.530-04:00   at internal/main/run_main_module.js:17:47
package.json

Cluster server started on 56
events.js:292
      throw er; // Unhandled 'error' event
      ^

Error: write EPIPE
    at process.target._send (internal/child_process.js:835:20)
    at process.target.send (internal/child_process.js:706:19)
    at sendHelper (internal/cluster/utils.js:26:15)
    at send (internal/cluster/child.js:193:10)
    at EventEmitter.cluster._setupWorker (internal/cluster/child.js:46:3)
    at initializeClusterIPC (internal/bootstrap/pre_execution.js:337:13)
    at prepareMainThreadExecution (internal/bootstrap/pre_execution.js:62:3)
    at internal/main/run_main_module.js:7:1
Emitted 'error' event on Worker instance at:
    at process.<anonymous> (internal/cluster/worker.js:29:12)
    at process.emit (events.js:315:20)
    at internal/child_process.js:839:39
    at processTicksAndRejections (internal/process/task_queues.js:79:11) {
  errno: -32,
  code: 'EPIPE',
  syscall: 'write'
}
events.js:292
      throw er; // Unhandled 'error' event
      ^

Error: write EPIPE
    at process.target._send (internal/child_process.js:835:20)
    at process.target.send (internal/child_process.js:706:19)
    at sendHelper (internal/cluster/utils.js:26:15)
    at send (internal/cluster/child.js:193:10)
    at EventEmitter.cluster._setupWorker (internal/cluster/child.js:46:3)
    at initializeClusterIPC (internal/bootstrap/pre_execution.js:337:13)
    at prepareMainThreadExecution (internal/bootstrap/pre_execution.js:62:3)
    at internal/main/run_main_module.js:7:1
Emitted 'error' event on Worker instance at:
    at process.<anonymous> (internal/cluster/worker.js:29:12)
    at process.emit (events.js:315:20)
    at internal/child_process.js:839:39
    at processTicksAndRejections (internal/process/task_queues.js:79:11) {
  errno: -32,
  code: 'EPIPE',
  syscall: 'write'
}

Any help would be greatly appreciated.

How often does it reproduce? Is there a required condition?

No response

What is the expected behavior?

No response

What do you see instead?

No response

Additional information

No response

aduh95 commented 3 years ago

This seems to be related to this part of Node.js: https://github.com/nodejs/node/blob/5ce015ec72be98f064041d1bf5c3527a89c276cc/lib/events.js#L422-L429

It looks like your code is trying to add an event listener to undefined... Did this error appeared after an upgrade of a Node.js version? If so, could you share the version number you were using before? If not, it's more likely a bug in your code (or one dependency you're using) and not a bug inn Node.js, and we should transfer this issue to nodejs/help.

twigs67 commented 3 years ago

@aduh95 We did not. It's being deployed in docker. Ok, I'll post it there. Thanks for the prompt response.

twigs67 commented 3 years ago

Wait @Mesteery @aduh95 can we reopen this? I mistakenly opened that duplicat.

Mesteery commented 3 years ago

It's already open. By the way, could you share this line /usr/src/app/dist/src/core/node-cluster.js:40 so we can more easily help you?

twigs67 commented 3 years ago

@Mesteery

let AppClusterService = class AppClusterService {                                                                                                                                                                                       
    static clusterize(callback) {                                                                                                                                                                                                       
        if (cluster_1.isMaster) {                                                                                                                                                                                                       
            console.log(`Master server started on ${process.pid}`);                                                                                                                                                                     
            for (let i = 0; i < numCPUs; i++) {                                                                                                                                                                                         
                (0, cluster_1.fork)();                                                                                                                                                                                                  
            }                                                                                                                                                                                                                           
            (0, cluster_1.on)('exit', (worker, code, signal) => {               // line 40                                                                                                                                                         
                console.log(`Worker ${worker.process.pid} died. Restarting`);                                                                                                                                                           
                (0, cluster_1.fork)();                                                                                                                                                                                                  
            });                                                                                                                                                                                                                         
        }                                                                                                                                                                                                                               
        else {                                                                                                                                                                                                                          
            console.log(`Cluster server started on ${process.pid}`);                                                                                                                                                                    
            callback();                                                                                                                                                                                                                 
        }                                                                                                                                                                                                                               
    }                                                                                                                                                                                                                                   
};  
aduh95 commented 3 years ago

What's the reason for using (0, cluster_1.on)( instead of cluster_1.on(? That's the cause of your error as this syntax doesn't set the this of the method to the expected instance:

class Foo{ bar(){ return this } }

let foo = new Foo;

console.log(foo.bar() === foo); // true
console.log((0, foo.bar)() === undefined); // true
twigs67 commented 3 years ago

@aduh95 you were correct. It was the node-cluster that was causing the issue. We have just removed it for now, but we would like to get this working. This is the original code (code snippet above is the compiled version).

// node-cluster.ts
import { Injectable } from '@nestjs/common';
import { ConfigService } from '@services';

 import * as cluster from 'cluster';
 import * as os from 'os'

const numCPUs = os.cpus().length;

@Injectable()
export class ClusterService {
  static clusterize(callback: Function): void {
    if (cluster.isMaster && !ConfigService.isDevEnvironment()) {
      console.log(`MASTER SERVER (${process.pid}) IS RUNNING `);

      for (let i = 0; i < numCPUs; i++) {
        cluster.fork();
      }

      cluster.on('exit', (worker, code, signal) => {
        console.log(`worker ${worker.process.pid} died`);
      });
    } else {
      callback();
    }
  }
}

Any idea how I might fix this?

aduh95 commented 3 years ago

Maybe something related to @Injectable()? Maybe there's an option you can add to disable this behavior?

Den-dp commented 7 months ago

Looks like when transpiler (babel in my case) tries to output commonjs modules, we end up with the code that loses this.

F.e. the following code...

import { on } from 'process';

on('beforeExit', () => console.log('exit'));

...are getting transpiled to this:

"use strict";

var _process = require("process");
(0, _process.on)('beforeExit', () => console.log('exit'));

Here is the example in babel playground

RedYetiDev commented 2 months ago

Is this issue still occuring? If not, feel free to self-close.