0

When I run npm run prod, I get the error:

enter image description here

My package.json script is as follows:

    "scripts": {
    "build": "npm run clean && babel src/index.js --out-dir dist --copy-files",
    "clean": "rm -rf dist",
    "test": "jest --coverage --watch",
    "start": "babel-node — exec src/index.js",
    "dev": "nodemon  — exec babel-node src/index.js",
    "prod": "node dist/index.js"

My directory structure:

dist/
 index.js // the compiled file
node_modules
src/
  /config
  /controllers
  /dao
  /middlewares
  /routes
  /services
 index.js
 server.js

Server.js is my express app and it is exported to Index.js where I connect to Mongodb. Line 9, as stated in the error stack from the compiled Index.js is:

var app = require('./server'); // not being found

I'm not sure why the dependency is not found. Below is the index.js:

require('dotenv').config()
const app = require('./server')
const chalk = require('chalk')
const OrdersDAO = require('./dao/ordersDAO')
// module to connect to MongoClient
const { MongoClient } = require('mongodb')
const uri = process.env.MONGODB_CONN_STR

const client = new MongoClient(uri, {
  useNewUrlParser: true,
  poolSize: 50,
  useUnifiedTopology: true,
})

const connectToMongoDB = async () => {
  try {
    const conn = await client.connect()
    const orders = conn
      .db(process.env.DATABASE)
      .collection(process.env.COLLECTION)
    await OrdersDAO.injectDB(client)
    await listDatabases(client)
    app.listen(process.env.PORT, () => {
      console.log(`listening on port ${process.env.PORT}`)
    })
  } catch (e) {
    console.error(`Index.js ~~~ Unable to get database.collection: ${e}`)
    // Exit Gracefully ~~~ https://nodejs.dev/learn/how-to-exit-from-a-nodejs-program
    process.on('SIGTERM', () => {
      server.close(() => {
        console.log('Process terminated')
      })
    })
  } finally {
    //  when uncommented ~~~ OrdersDAO.addOrder() ~~~ Unable to post order:) MongoError: Topology is closed, please connect
    // console.log(chalk.magentaBright('Mongo Connection is closing ~~~~'))
    // await client.close()
  }
}

const listDatabases = async (client) => {
  try {
    const dbList = await client.db().admin().listDatabases()
    console.log(chalk.magentaBright('Databases:'))
    dbList.databases.forEach((db) => {
      console.log(chalk.greenBright(` - ${db.name}`))
    })
  } catch (error) {
    console.error(error)
  }
}

connectToMongoDB()

server.js

onst express = require('express')
const bodyParser = require('body-parser')
const cors = require('cors')
require('dotenv').config()
const orders = require('./routes/orders')

const app = express()

// http://expressjs.com/en/4x/api.html#express.urlencoded
app.use(cors())
app.use(express.urlencoded({ extended: true }))

/* stackoverflow.com/questions/24330014/bodyparser-is-deprecated-express-4
parse the incoming requests with JSON payloads */
app.use(express.json())

// Register api routes
app.use('/', orders) //(req, res) => res.send(console.log('Time:', Date.now())))
app.use('/admin/', orders)
app.use('/admin/:id', orders)
/*
TODO - fall through route handler
*/
// app.use("*", (req, res) => res.status(404).json({ error: "not found" }));

module.exports = app
Kevin T.
  • 668
  • 3
  • 12
  • 29
  • If the compiled file is one level lower, you'll need to use `../`. I'd probably look into using `__dirname` and `path.resolve` instead? – evolutionxbox Aug 04 '21 at 15:11
  • Where would I use __dirname and path.resolve in index.js? I can already see the next error being that it won't find ('./dao/ordersDAO'). @evolutionbox I made edits to add the files. – Kevin T. Aug 04 '21 at 15:29
  • Maybe something like `path.resolve([__dirname, 'server.js'])`? – evolutionxbox Aug 04 '21 at 15:38
  • 1
    This is what I did, and this may be completely wrong and hacky. I changed my build script to this: `"build": "npm run clean && babel ./src --out-dir dist --copy-files"` where instead of index.js I used ./src, the whole src folder was compiled. I ran npm run build script and then npm run prod. The next error was: a regenerator runtime error: `/Users/kevinturney/Vue/cookie_mvp_next/cookie_server/dist/dao/ordersDAO.js:30 var _injectDB = _asyncToGenerator( /*#__PURE__*/regeneratorRuntime.mark(function _callee(clientConnection) { ^ – Kevin T. Aug 04 '21 at 15:49
  • 1
    That's a valid approach too. Consider adding it as an answer? – evolutionxbox Aug 04 '21 at 15:50
  • ... So I npm installed 'core-js/stable', and 'regenerator-runtime/runtime'. From there in index.js I required them and the scripts all worked. – Kevin T. Aug 04 '21 at 15:53

2 Answers2

1

It seems you have to build the whole src folder, not only index.js Do that and then you'll see both index.js and server.js files inside the dist folder.

To achieve this, change your build command in package.json to:

npm run clean && babel src --out-dir dist --copy-files
0

The solution was to modify the build script to:

"build": "npm run clean && babel ./src --out-dir dist --copy-files",

After that, based on my dependencies in the package.json, I had a regenerator runtime error:


/Users/kevinturney/Vue/cookie_mvp_next/cookie_server/dist/dao/ordersDAO.js:30 var injectDB = _asyncToGenerator( /*#__PURE_*/regeneratorRuntime.mark(function _callee(clientConnection) { ^ – 

I then npm installed regenrator-runtime and core-js, see Dev.to article. Finally from there, I imported them into index.js.

A final note, when running a test on index.js, I had regenerator-runtime is not defined, so in /tests/indes.spec.js, I imported it:

import 'regenerator-runtime/runtime'

Everything works.

Kevin T.
  • 668
  • 3
  • 12
  • 29