Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Error: EBADF: bad file descriptor, write #250

Open
hansaliyad1 opened this issue Nov 17, 2020 · 7 comments
Open

Error: EBADF: bad file descriptor, write #250

hansaliyad1 opened this issue Nov 17, 2020 · 7 comments

Comments

@hansaliyad1
Copy link

I have an express server application that handles a few NodeJS API and hosts the Angular 10 app. In production, I use process manager PM2. When the user visits https://domainname.com/webpage, the app crashes with the below error. PM2 restarts the application. To continue, the user has to refresh the webpage.

Error: EBADF: bad file descriptor, write
    at Socket._write (internal/net.js:54:25)
    at doWrite (_stream_writable.js:403:12)
    at writeOrBuffer (_stream_writable.js:387:5)
    at Socket.Writable.write (_stream_writable.js:318:11)
    at Array.logRequest (C:\NODE_APPS\website\node_modules\morgan\index.js:130:14)
    at listener (C:\NODE_APPS\website\node_modules\on-finished\index.js:169:15)
    at onFinish (C:\NODE_APPS\website\node_modules\on-finished\index.js:100:5)
    at callback (C:\NODE_APPS\website\node_modules\ee-first\index.js:55:10)
    at ServerResponse.onevent (C:\NODE_APPS\website\node_modules\ee-first\index.js:93:5)
    at ServerResponse.emit (events.js:327:22)
    at onFinish (_http_outgoing.js:723:10)
    at onCorkedFinish (_stream_writable.js:673:5)
    at afterWrite (_stream_writable.js:490:5)
    at afterWriteTick (_stream_writable.js:477:10)
    at processTicksAndRejections (internal/process/task_queues.js:83:21) {
       errno: 'EBADF',
       syscall: 'write',
      code: 'EBADF'
   }
GetRegValue(): Unable to RegOpenKeyEx () The system cannot find the file specified.

If I don't use process manager PM2 and run the application like node bin\www, everything works with no problem. It does randomly crashes with no error on the console. I am using an error handler called strong-error-handler. Application started using node bin\www crashes randomly but less frequently. Application started using PM2 crashes as soon as the user access the webpage. The PM2 logs mention about the morgan. I don't know what the error message means but I will really appreciate any assistance in the correct direction. Thank you!

@dougwilson
Copy link
Contributor

Are you passing in the stream option to morgan in your app? It seems like the error is coming from whatever the stream that morgan is attempting to write to.

@hansaliyad1
Copy link
Author

hansaliyad1 commented Nov 18, 2020

Are you passing in the stream option to morgan in your app? It seems like the error is coming from whatever the stream that morgan is attempting to write to.

I am sorry! I am not sure what would be the stream option. I use morgan with default configuration you get when you setup express. Currently, I have below in app.js

const logger = require('morgan');

app.use(logger('dev'));

Here, app is const app = express();

@hansaliyad1
Copy link
Author

I also tried using forever instead of PM2 to find out if there is any difference.

Error: EBADF: bad file descriptor, write
    at Socket._write (internal/net.js:54:25)
    at doWrite (_stream_writable.js:403:12)
    at writeOrBuffer (_stream_writable.js:387:5)
    at Socket.Writable.write (_stream_writable.js:318:11)
    at Array.logRequest (C:\NODE_APPS\website\node_modules\morgan\index.js:130:14)
    at listener (C:\NODE_APPS\website\node_modules\on-finished\index.js:169:15)
    at onFinish (C:\NODE_APPS\website\node_modules\on-finished\index.js:100:5)
    at callback (C:\NODE_APPS\website\node_modules\ee-first\index.js:55:10)
    at ServerResponse.onevent (C:\NODE_APPS\website\node_modules\ee-first\index.js:93:5)
    at ServerResponse.emit (events.js:327:22)
    at onFinish (_http_outgoing.js:723:10)
    at onCorkedFinish (_stream_writable.js:673:5)
    at afterWrite (_stream_writable.js:490:5)
    at afterWriteTick (_stream_writable.js:477:10)
    at processTicksAndRejections (internal/process/task_queues.js:83:21)
Emitted 'error' event on Socket instance at:
    at errorOrDestroy (internal/streams/destroy.js:108:12)
    at onwriteError (_stream_writable.js:418:5)
    at onwrite (_stream_writable.js:445:5)
    at Socket._write (internal/net.js:58:14)
    at doWrite (_stream_writable.js:403:12)
    [... lines matching original stack trace ...]
    at afterWrite (_stream_writable.js:490:5) {
  errno: 'EBADF',
  syscall: 'write',
  code: 'EBADF'
}
GetRegValue(): Unable to RegOpenKeyEx () The system cannot find the file specified.

@dougwilson
Copy link
Contributor

Can you provide full steps to reproduce the issue? Please include a complete app (could just use the example from the readme if it reproduces the issue) and the instructions for how to run it under pm2 and what to do to cause the error. I just tried a simple morgan app under pm2 but didn't have any error, so just need complete reproduction instructions so I can help look into the issue, thank you!

@hansaliyad1
Copy link
Author

hansaliyad1 commented Nov 18, 2020

Little bit on folder structure.

Website
-- bin
---- config.js
---- www
-- client //This is Angular Application
-- server
---- asset
---- config
------ mailer_config.js
------ index.js //ODBC Connection
---- controllers
---- functions
---- models
---- queries
---- routes
-- static // Error HTML Pages
-- .env
-- .gitignore
-- app.js
-- package.json

Here is bin/www file

#!/usr/bin/env node

/**
 * Module dependencies.
 */
require('dotenv').config();

const app         = require('../app');
const debug       = require('debug')('hunterwebsite:server');
const http        = require('http');
const mongoose    = require('mongoose');
mongoose.Promise  = global.Promise;
const config      = require('./config');
const { stringify } = require('querystring');

/**
 * MongoDB Connection
 */

mongoose.connect(config.uri, { useNewUrlParser: true }, (err) => {
  // Check if database was able to connect
  if (err) {
    console.log('Could NOT connect to database: ', err); // Return error message
  } else {
    console.log('Connected to MongoDB ' + config.db); // Return success message
  }
});

/**
 * Get port from environment and store in Express.
 */
if (process.env.NODE_ENV === 'production') { process.env.PORT = '3000' }
else { process.env.PORT = '3010' }
const port = normalizePort(process.env.PORT || '3000');
app.set('port', port);

/**
 * Create HTTP server.
 */

const server = http.createServer(app);

/**
 * Listen on provided port, on all network interfaces.
 */

server.listen(port, () => {
    console.log('Listening on port ' + port + ' in ' + process.env.NODE_ENV + ' mode  ');
});
server.on('error', onError);
server.on('listening', onListening);

/**
 * Normalize a port into a number, string, or false.
 */

function normalizePort(val) {
  const port = parseInt(val, 10);

  if (isNaN(port)) {
    // named pipe
    return val;
  }

  if (port >= 0) {
    // port number
    return port;
  }

  return false;
}

/**
 * Event listener for HTTP server "error" event.
 */

function onError(error) {
  if (error.syscall !== 'listen') {
    throw error;
  }

  const bind = typeof port === 'string'
    ? 'Pipe ' + port
    : 'Port ' + port;

  // handle specific listen errors with friendly messages
  switch (error.code) {
    case 'EACCES':
      console.error(bind + ' requires elevated privileges');
      process.exit(1);
      break;
    case 'EADDRINUSE':
      console.error(bind + ' is already in use');
      process.exit(1);
      break;
    default:
      throw error;
  }
}

/**
 * Event listener for HTTP server "listening" event.
 */

function onListening() {
  const addr = server.address();
  const bind = typeof addr === 'string'
    ? 'pipe ' + addr
    : 'port ' + addr.port;
  debug('Listening on ' + bind);
}

Here is app.js file

const createError     = require('http-errors');
const compression     = require('compression');
const express         = require('express');
const errorHandler    = require('strong-error-handler');
const path            = require('path');
const logger          = require('morgan');
const cookieParser    = require('cookie-parser');
const bodyParser      = require('body-parser');
const cors            = require('cors');


const app = express();
app.use(compression());
const router = express.Router();

// Require all routes into the application.
const public_routes = require('./server/routes/public')(router);
const gr_enroll_routes = require('./server/routes/gr-enroll')(router);

app.use(cors({ origin: 'http://localhost:4200' }));
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({extended: false}));
app.use(cookieParser());
app.use(express.static(__dirname + '/dist'));

// Use all routes into the application.
app.use('/xyzxyz', public_routes);
app.use('/xyz', gr_enroll_routes);


// Connect server to Angular 2 Index.html
app.get('*', (req, res) => {
    res.sendFile(path.join(__dirname + '/dist/index.html'), (err) => {
        if (err) {
            res.sendFile(path.join(__dirname + '/static/index.html'));
        }
    });
});

app.use(errorHandler({
    debug: app.get('env') === 'development',
    log: true,
}));

module.exports = app;

I use git. I pull new updates from the git repository to the production server. I start the application using pm2 start bin\www --name www. The application comes up and works fine. Then, when the user tries to submit a form, my functions compare the form data against the ODBC data source using the ODBC package (https://www.npmjs.com/package/odbc), that's when the application crashes with the above error message. This only happens if the application is started with a process manager like PM2 or forever. If I use node bin\www to start the application, everything works smoothly. I have tried this on another server and I get the same results.

EDIT: Hey! I appreciate your help with this. I have been googling and trying to find what is wrong. Thank you for your time.

@saostad
Copy link

saostad commented Jul 19, 2022

Hey, did you find any solution? I have this problem and can't find a way to fix it.

@GeraldoAnjos
Copy link

Ei, saostad!
As vezes o antivírus impede que o Visual Studio Code faça alterações nos arquivos do seu repositório. Eu consegui resolver adicionando a pasta do meu repositório a exclusão de segurança do Windows. Pesquise por "exclusões na segurança do Windows". ou Link: https://support.microsoft.com/pt-br/topic/o-que-s%C3%A3o-exclus%C3%B5es-na-seguran%C3%A7a-do-windows-8b248399-5e63-4a4b-897f-52ea2dddb962#:~:text=Para%20adicionar%20uma%20exclus%C3%A3o,selecione%20Adicionar%20ou%20remover%20exclus%C3%B5es.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

4 participants