0

I have an issue where I need to load express like this:

var express = require('express');
var app = express();

In order to get .static to work:

app.use(express.static(__dirname+'views'));

Any reason why I can't use shorthand:

var app = require('express')();

When I try the short hand it says express.static is undefined and my script won't run. Is this just a feature that's not supported by express?

allegory
  • 124
  • 1
  • 1
  • 10

2 Answers2

2

Any reason why I can't use shorthand:

var app = require('express')();

If you considered this statement from your script,

app.use(express.static(__dirname+'views'));

you are using static method of express.In order to use this method,you must import express first and store it in some variables like u did

var express = require('express');

From express#express.js

exports.static = require('serve-static');

static defined at class level.

then instantiate it like this

var app = express();

to get the access to object level(prototype) method and properties like app#use app#engine etc.

From express#application //line no 78

EDIT :

but then why can't I use app.static if I did var app = require('express')();

As I said,.static is the class level method and not the instance/object(prototype) level.

So,by var app = require('express')() you will get express instance / object (prototype) which dont have app.static method.So,you can't use.

Read more javascript-class-method-vs-class-prototype-method

Community
  • 1
  • 1
RIYAJ KHAN
  • 15,032
  • 5
  • 31
  • 53
1

This will work: const app = (() => require('express'))()();

But you still need express itself, so there literally is no real point to requiring twice.

Ezra Chang
  • 1,268
  • 9
  • 12
  • Didn't know I could put double() after a require, are there any other functions that could be used for? Yes, still have to require('express') into it's own variable to get static. – allegory Mar 16 '17 at 17:10