0
votes

I am currently trying to run node es6 with babel on a docker container and am running into some issues getting the app to start listening on port 3000. I can see where the app.js file is being processed as I am seeing the database connection code running. The problem seems to be even though app.js is getting called I am not seeing anything from /bin/www getting called which would result in the server listening on port 3000.

This is the command that is getting called to start the container:

nodemon ./bin/www -L --exec babel-node --inspect=0.0.0.0:56745

app.js: ……

(async () => {
    try {
        console.log('about to start the database connection... - 1');
        mongoose.set('useCreateIndex', true);
        mongoose.Promise = global.Promise;
        console.log('about to start the database connection... - 2');
        setTimeout(async () => {
            await mongoose.connect(process.env.DB_HOST, {useNewUrlParser: true});
        }, 60000);
        //await mongoose.connect(process.env.DB_HOST, {useNewUrlParser: true});
        console.log('about to start the database connection... - 3');

        let db = mongoose.connection;
        console.log('about to start the database connection... - 4');
        db.on('error', console.error.bind(console, 'MongoDB connection error:'));
        console.log('about to start the database connection... - 5');
    } catch (e) {
        console.log('We have an error.....');
        console.log(e);
    }
})()


let app = express();

app.use(logger('dev'));
app.use(express.json());
app.use(express.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));

app.use(helmet());
app.use(methodOverride());

// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'pug');

app.use('/', indexRouter);
app.use('/users', usersRouter);
app.use('/group', groupsRouter);

// catch 404 and forward to error handler
app.use(function(req, res, next) {
  next(createError(404));
});

// error handler
app.use((err, req, res, next) => {
    if (process.env.NODE_ENV === "development") {
        app.use((err, req, res, next) => {
            if (err instanceof NotFoundError) {
                //res.status(404).send(err.message);
                res.statusCode = 404;
                return res.json({
                    errors: [err.stack]
                });
            } else {
                //res.status(500).send('An error occurred while processing your request.');
                res.statusCode = 500;
                return res.json({
                    errors: [err.stack]
                    //errors: ['An error occurred while processing your request.']
                });
            }
        });
    }

    // production error handler
    // no stacktraces leaked to user
    console.log('about to begin configurations..... 7');
    if (process.env.NODE_ENV !== "development") {
        app.use((err, req, res, next) => {
            if (err instanceof NotFoundError) {
                //res.status(404).send(err.message);
                res.statusCode = 404;
                return res.json({
                    errors: [err.stack]
                });
            } else {
                //res.status(500).send('An error occurred while processing your request.');
                res.statusCode = 500;
                return res.json({
                    errors: [err.stack]
                    //errors: ['An error occurred while processing your request.']
                });
            }
        });
    }
});

module.exports = app;

/bin/www:

#!/usr/bin/env node

/**
 * Module dependencies.
 */

let app = require('../app');
let debug = require('debug’)(‘myapp:server');
let http = require('http');

/**
 * Get port from environment and store in Express.
 */

let port = normalizePort(process.env.PORT || '3000');
app.set('port', port);

/**
 * Create HTTP server.
 */

let server = http.createServer(app);

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

server.listen(port);
server.on('error', onError);
server.on('listening', onListening);

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

const normalizePort = (val) => {
  debug('port = ' + val);
  let 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.
 */

const onError = (error) => {
  debug('Houston we have a problem');
  if (error.syscall !== 'listen') {
    throw error;
  }

  let 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.
 */

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

.babelrc:

{
  "presets": ["env"],
   "plugins": ["transform-object-rest-spread", "transform-async-to-generator"]
}

Update:

The issue seems to be with node and the arrow operator. When I changed to the function keyword, it started working. I added the following to my .bablerc file:

{
  "presets": ["env"],
   "plugins": ["transform-object-rest-spread", "transform-async-to-generator", "transform-es2015-arrow-functions"]
}

but it is still an issue. How can I use the arrow operator with nodejs?

1
Based on your code, if you see that db connection output, then bin/www must be running (it is the thing that loads app.js). My guess is that somewhere in bin/www, after requiring app.js, you encounter an error. I'd look for any stdout or err logs from that process and see where they go.Elliot Nelson
Could this line be a problem: let port = normalizePort(process.env.PORT || '3000');, I am noticing that it is not getting past this function call. It seems to go past this line if I remove the process.env part. Could this be something with es6 and babel? Strange thing is that if I console.log the process.env.PORT I am getting 3000 as this is in the .env file. I literally have breakpoints everywhere.user1790300
You could try explicitly including process i.e. let process = require('process');.Elliot Nelson
It seems to be an issue with the arrow function and nodejs. Here is the exception I am getting: [Inside 'uncaughtException' event] TypeError: normalizePort is not a function.user1790300

1 Answers

0
votes

If you aren't able to progress past the normalizePort call, are you sure it exists at that time?

You need to move the definition of the function above the place you use it.

(If you are used to old, pre-ES6 "function hoisting" using vars and functions, you should note that that does not work with const and let statements.)