babel节点,无法让服务器监听端口

时间:2019-01-25 19:39:51

标签: node.js express docker-compose babel babel-node

我目前正在尝试在docker容器上使用babel运行节点es6,并且遇到一些问题,导致该应用程序开始在端口3000上进行侦听。我看到正在处理app.js文件的位置数据库连接代码正在运行。问题似乎是即使app.js被调用,我也没有从/ bin / www看到任何调用,这会导致服务器监听端口3000。

这是用来启动容器的命令:

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"]
}

更新

问题似乎出在节点和箭头运算符上。当我更改为function关键字时,它开始起作用。我在.bablerc文件中添加了以下内容:

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

但这仍然是一个问题。如何在nodejs中使用箭头运算符?

1 个答案:

答案 0 :(得分:0)

如果您无法通过normalizePort通话,您确定当时存在吗?

您需要将函数的定义移至使用位置上方。

(如果您习惯使用var和函数进行过旧的ES6之前的“函数提升”,则应注意,这不适用于const和let语句。)