Instantiating express - node.js

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?

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

This will work: const app = (() => require('express'))()();
But you still need express itself, so there literally is no real point to requiring twice.

Related

What is the difference between the two calls to express()

I have 2 require('express) calls.
First:
const express = require('express');
const app = express();
Second:
const Router = require('express');
const router = new Router();
What is the difference, why in the first we call a function, and in the second we create an object, if the methods are the same in both (use, get, post, etc)?
I think your question missed something. Your second example shows this:
const Router = require('express');
... but I think you meant to do this:
const Router = require('express').Router;
... regardless, the following should help you better understand.
In express, you can think of Routers as little mini applications... lightweight express apps... which have their own routing. In fact, the main "express" object is itself a Router. For example, you might have a bunch of endpoints for managing users:
// ./routes/user-routes.js
const userRoutes = new express.Router();
userRoutes.get('/', getAllUsers);
userRoutes.get('/:userId', getUserById);
userRoutes.post('/', createUser);
userRoutes.put('/:id', updateUser);
userRoutes.delete('/:id', removeUser);
Notice how none of the urls have anything like /users/ inside them. This is important because this little mini app can now be "mounted" (for lack of better terms) in a larger express app like follows:
const express = require('espress');
const userRoutes = require('./routes/user-routes');
const app = express();
app.use('/path/to/users', userRoutes);
Notice how the userRoutes were "mounted" on the /path/to/users such that all user requests will happen to the following URLs:
GET /path/to/users - get all users
GET /path/to/users/1234 - get user with id "1234"
... you get the point
This is mostly a convenient way to think about your app as a bunch of smaller mini apps which are orchestrated together.
Your second call is incorrect, you are just calling (requiring) express which is similar to your first call.
I never did const router = new Router();, so I'm not sure what that accomplish.
I generally do-
const router = require('express').Router();
router.get();
Even though with your first call you can do
app.get() and app.post()
According to express explanation
express.Router class is used to create modular, mountable route handlers. A Router instance is a complete middleware and routing system
Read more about it here
GeekforGeeks explains express.Router() very well

React not recognizing Express

In my jsx file, I have the following:
var express = require('express');
var myExpress = express();
var http = require('http');
var app = http.createServer(myExpress);
var { Server } = require("socket.io");
var myio = new Server(app);
However, the browser says "Uncaught TypeError: express is not a function"
I have tried importing express with an import statement, as well as making my project a module in my package.json. What is weird is that when I use the same code in a regular js file in the same folder, it works perfectly well. This code was the code in every single one of the tutorials, so I am at a loss. Thank you.
Express is node framework you can't use it in react.
I think you need https://v5.reactrouter.com/web/guides/quick-start

What is the second pair of parenthesis in "require('express')()" in node.js?

I'm following the socket.io chat application tutorial here - https://socket.io/get-started/chat/
and it's using express framework. There's a code in the tutorial that is:
var app = require('express')();
var http = require('http').Server(app);
and if I just use 'require('express')' without the second parenthesis it doesn't work. What does the second parenthesis do and where could I find documentation for the syntax?
The type returned from require('express') is a function. The second set of parenthesis is you actually invoking the function to create an instance of an express app.
It's the equivalent of you doing
const express = require('express');
const app = express();
The require('express') call returns a function and hence you need to call that returned function in order to initialisation an express app. For example, the main entry file of express might look like
function one(){/*some code here*/}
function two(){/* some other code here*/ }
Module.exports = one;
So essentially what happens is that when you require express the above code is included and the one function is exported for you to use and hence you need to call that function that's why you have that extra parenthesis

Can I pass variable to required file?

In express, I'm trying to move my minification to a requierd file:
app.js:
var app = express();
var minify = require("./minify.js");
In that file I try to set my template engine.
minify.js:
var app = express();
app.engine('html', mustacheExpress());
Later when I try to use to use the rendering engine in app.js, I get the error that no template-engine is set. It works if I run it all in the same file. I think the problem is that I declare the app-variable twice. How can I pass the app-variable into minify.js?
The problem is that you define new app variable, and you currently instantiate brand new express instance by calling express().
What you need to do is start using functions so that you can pass params (there are other methods too, but this is one that will work for you):
// app.js
var app = express();
var minify = require('./minify'); // don't include .js!
minify(app); // CALL the function that minify.js exports, passing params
// minify.js
module.exports = function(app) {
// because app comes as a parameter, it's the very same you've created in app.js
app.engine('html', mustacheExpress());
}
Again, there are many different methods and maybe proper approaches, depending on what you want to do, but this will do the job in your case. Read more about NodeJS and it's require system.
You can pass 'app' from app.js to your minify by using function in your module like Andrey said. You can do it like this too for example :
minify.js
module.exports = {
setAppEngine : function(app) {
app.engine( [...] );
}
}
And calling it like this in your app.js:
app.js
var app = express();
var minify = require("./minify.js").setAppEngine(app);
This solution is very useful because you can set and call others methods in minify.js. For example, you can do with the same code in minify.js:
app.js
var app = express();
var minify = require("./minify.js");
minify.setAppEngine(app);

custom module not defined in nodejs express app

we made a custom module for express app but getting this error somename is not defined
here is our code
app.js
var express = require('express');
var path = require('path');
var favicon = require('serve-favicon');
var logger = require('morgan');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');
var somename = require('./somename/common');
// console.log(wahapar.ucfirst("d"));
var routes = require('./routes/index');
var users = require('./routes/users');
common.js
module.exports = {
ucfirst: function(str){
// discuss at: http://phpjs.org/functions/ucfirst/
// original by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
// bugfixed by: Onno Marsman
// improved by: Brett Zamir (http://brett-zamir.me)
// example 1: ucfirst('kevin van zonneveld');
// returns 1: 'Kevin van zonneveld'
str += '';
var f = str.charAt(0).toUpperCase();
return f + str.substr(1);
},
};
ejs view
<%= somename.ucfirst("this is a string") %>
while console.log(somename.ucfirst("d")); is showing output in the terminal
You should pass your module as a local variable into express app.
app.locals.somename = require('./somename/common');
Then you will be able to use inside ejs templates.
From the express docs app.locals
The app.locals object is a JavaScript object, and its properties are
local variables within the application.
Once set, the value of app.locals properties persist throughout the
life of the application, in contrast with res.locals properties that
are valid only for the lifetime of the request.
You can access local variables in templates rendered within the
application. This is useful for providing helper functions to
templates, as well as app-level data. Locals are available in
middleware via req.app.locals

Resources