Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Issue with consign and express paths

I'm currently working on some university coursework, which is essentially an API written in express. We're allowed to use other packages as long as we follow the spec.

I'm trying to use consign for autoloading my models, middleware and routes. The problem I'm facing is the folder structure that we have to follow.

coursework
|-- artifact
|   |-- server
|   |   |-- api
|   |   |   |-- models
|   |   |   |   `-- stories.js
|   |   |   |-- middleware
|   |   |   |   `-- stories.js
|   |   |   `-- routers
|   |   |       `-- stories.js
|   |   |-- node_modules
|   |   |-- package.json
|   |   |-- package-lock.json
|   |   `-- server.js
|   `-- utilities
|-- node_modules
|-- webpages
|-- package.json
|-- package-lock.json
`-- test.js

Inside of artifact is where all of our code goes, nothing else is touched. The root directory that contains test.js is where we will be assessed. From the root we run npm test (QUnit) and then it lists which tests have passed and which have failed.

The problem is we have to start our server from the root directory by calling node artifact/server which is fine because it calls artifact/server/server.js.

Inside of artifact/server/server.js I have the following code to initialise consign:

consign({ cwd: './artifact/server/api' })
    .include('models')
    .then('middleware')
    .then('routers')
    .into(app);

When I run node artifact/server from the root directory I get the following error:

Consign error

What's frustrating is if I change consign's cwd property to api and then start the server inside of artifact/server by calling node server.js it works perfectly fine.

The problem is I need to be able to start the server from the root directory. I'm completely stuck as I do not know how I can modify consign to work from the root directory.

Any ideas?

like image 520
Matt Kent Avatar asked Oct 28 '22 21:10

Matt Kent


1 Answers

I managed to find a solution to my problem and felt that I should post an answer to help others.

Essentially, as shown above I was using a relative path like so:

consign({ cwd: './artifact/server/api' })
    .include('models')
    .then('middleware')
    .then('routers')
    .into(app);

which when called from the root directory resulted in consign not working. This can be fixed by making use of path

I added this at the top of my server.js file:

const path = require('path');

and then changed my consign init to:

consign({ cwd: path.join(__dirname, 'api') })
    .include('models')
    .then('middleware')
    .then('routers')
    .into(app);

This then fixed my issue!

like image 182
Matt Kent Avatar answered Nov 01 '22 02:11

Matt Kent