1

Let me start with some statements

-> (Object instanceof Function) because object constructor is a function

-> (Function instanceof Object) because functions are objects

Now my question is : How can I simulate the express.js object behaviour ?

const express = require("express");
const app = express(); // express here is a function
app.use(express.json()) // now here express is an object

This works fine in nodejs and i believed that express is basically an object and when you call express() you reference the object constructor. However things seem to be a bit different.

Trying to consider it as a class will also fail because you don't instantiate it as new. And, if you try to simulate it as a function, you can't simulate it as an object.

I've appended 3 of my attempts to simulate this behavior

// Trying to simulate it with a function

var express = () => { 
  this.json = () => {console.log("json")}
  return {
    listen : () =>{ console.log("listen !") },
    use    : () =>{ console.log("use !")  }
  }
}

const app = express(); // ok
      app.listen();    // ok
      app.use();       // ok

express.json(); // fail

// Trying to simulate it with a class
class express{
  constructor(){
    return {
      listen : () => { console.log("listen !") },
      use    : () => { console.log("use !")  }
    }
  }
  json(){console.log("json")}
}

const app = express(); // Class constructor express cannot be invoked without 'new'",
app.listen();  
app.use();
      
express.json(); // not instanciated

// Trying to simulate it as an object
var express = {
    constructor : ()=>{ // does not overwrite constructor 
      return {
          listen : () =>{ console.log("listen !") },
          use    : () =>{ console.log("use !")  }
      }
    },
    json : ()=>{console.log("json")}
  }
  
const app = express(); // "message": "Uncaught TypeError: express is not a function",
      app.listen();    
      app.use();       
express.json()
Ionut Eugen
  • 481
  • 2
  • 6
  • 27
  • 1
    Did you try doing `express = function() { }`, then on the next line give it additional properties with `express.json = function() { }`? – Wyck Sep 22 '22 at 13:23
  • "*This works fine in nodejs and i believed that express is basically an object and when you call express() you reference the object constructor.*" no, `express` is just a function that also has properties, since it's an object. – VLAZ Sep 22 '22 at 13:27

0 Answers0