Home > Enterprise >  is is possible to extract express use into another file?
is is possible to extract express use into another file?

Time:12-16

I'm having a simple express app but I think the file is so messy and I'm trying to organize it so for example this piece of code

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

is it possible to separate it into another file and require it on the main file?

CodePudding user response:

Yes, you can try specifying the directory name, I mean something like:

http://localhost:3001/styles.css

To have /styles in your request URL, you can use:

app.use("/styles", express.static(__dirname   '/styles'));

Other method could be:

//Serve static content for the app from the "public" directory in the application directory.

// GET /style.css etc
app.use(express.static(__dirname   '/public'));

// Mount the middleware at "/static" to serve static content only when their request path is prefixed with "/static".

// GET /static/style.css etc.
app.use('/static', express.static(__dirname   '/public'));

app.use('/img',express.static(path.join(__dirname, 'public/images')));
app.use('/js',express.static(path.join(__dirname, 'public/javascripts')));
app.use('/css',express.static(path.join(__dirname, 'public/stylesheets')));

Then just test the Static request example in socket.io or other of your preference:

http://testexpress.lite.c9.io/js/socket.io.js
  • Related