Import app Unexpected Identifier ES6 module in ExpressJS

Branch (Chapter 07 Section 04)

I’ve been following David Herron’s Notes sample in NodeJS Fourth Edition and again in NodeJS Complete Reference Guide

This section is all about updating to ES6 modules… I’ve been using VSCodes automated conversion and then checking it against the book for comparisons.

I’ve found workarounds, but I’ve had to go outside his book and it leaves me wondering if code samples in the next chapters will still be compatible or what I might be missing in this section. I’ve tried dropping the , {set} and I’ve tried just wrapping {app} in a bracket, that still didn’t work.

any general advice would be appreciated, especially if you’ve read through either of tutorials before













app.mjs

import { ensureDir } from 'fs-extra';
import createError from 'http-errors';
import express, { json, urlencoded, static } from 'express';
import { dirname, join } from 'path';
import cookieParser from 'cookie-parser';
import logger from 'morgan';

import DBG from 'debug';
const debug = DBG('notes:debug');
const error = DBG('notes:error');

import { router as indexRouter } from './routes/index';
// const users = require('./routes/users');
import { router as notesRouter } from './routes/notes';

// Workaround for lack of __dirname in ES6 modules
import dirname from './dirname.js';
const { __dirname } = dirname;

const app = express();

// chapter 07 section 03
import rfs from 'rotating-file-stream';
var logStream;
// Log to a file if requested
if (process.env.REQUEST_LOG_FILE) {
  (async () => {
    let logDirectory = dirname(process.env.REQUEST_LOG_FILE);
    await ensureDir(logDirectory);
    logStream = rfs(process.env.REQUEST_LOG_FILE, {
      size: '10M', // rotate every 10 MegaBytes written
      interval: '1d',  // rotate daily
      compress: 'gzip' // compress rotated files
    });
  })().catch(err => { console.error(err); });
}

// view engine setup
app.set('views', join(__dirname, 'views'));
// app.set('view engine', 'hbs');
// chapter 05 section 04
import { registerPartials } from 'hbs';
app.set('view engine', 'hbs');
registerPartials(join(__dirname, 'partials'));

// app.use(logger('dev'));
// chapter 07 section 03
app.use(logger(process.env.REQUEST_LOG_FORMAT || 'dev', {
  stream: logStream ? logStream : process.stdout
}));
app.use(json());
app.use(urlencoded({ extended: false }));
app.use(cookieParser());
app.use(static(join(__dirname, 'public')));

// <!-- jQuery first, then Popper.js, then Bootstrap JS -->
app.use('/assets/vendor/jquery', static(
  join(__dirname, 'node_modules', 'jquery', 'dist')));
app.use('/assets/vendor/popper.js', static(
  join(__dirname, 'node_modules', 'popper.js', 'dist')));
app.use('/assets/vendor/bootstrap/js', static(
  join(__dirname, 'node_modules', 'bootstrap', 'dist', 'js')));
app.use('/assets/vendor/bootstrap/css', static(
  join(__dirname, 'theme/slate')));
app.use('/assets/vendor/feather-icons', static(
  join(__dirname, 'node_modules', 'feather-icons', 'dist')));

app.use('/', indexRouter);
// app.use('/users', usersRouter);
app.use('/notes', notesRouter);

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

process.on('uncaughtException', function (err) {
  error("I've crashed!!! - " + (err.stack || err));
});

process.on('unhandledRejection', (reason, p) => {
  error(`Unhandled Rejection at: ${util.inspect(p)} reason: ${reason}`);
});

if (app.get('env') === 'development') {
  app.use(function (err, req, res, next) {
    // util.log(err.message); 
    res.status(err.status || 500);
    error((err.status || 500) + ' ' + error.message);
    res.render('error', {
      message: err.message,
      error: err
    });
  });
}

// error handler
app.use(function (err, req, res, next) {
  // set locals, only providing error in development
  res.locals.message = err.message;
  res.locals.error = req.app.get('env') === 'development' ? err : {};

  // render the error page
  res.status(err.status || 500);
  res.render('error');
});

export default app;

www.mjs

#!/usr/bin/env node

/**
 * Module dependencies.
 */

import app, { set } from '../app.mjs';
import app from '../app.mjs';
import DBG from 'debug';
const debug = DBG('notes:server-debug');
const error = DBG('notes:server-error');
// var debug = require('debug')('notez:server');
import { createServer } from 'http';

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

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

/**
 * Create HTTP server.
 */

var server = 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.
 */

function normalizePort(val) {
  var 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;
  }

  var 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() {
  var addr = server.address();
  var bind = typeof addr === 'string'
    ? 'pipe ' + addr
    : 'port ' + addr.port;
  debug('Listening on ' + bind);
}

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.