nodejs require multiple files - node.js

can some one explain, I am confused by the bodyparser library in nodeJS.
There is this line
var deprecate = require('depd')('body-parser')
If I look for IDE definitions for deprecate, it points to the depd library, but I am not sure what the second (body-parser) parameter doing here?

The line you ask about "activates" depd library for body-parser library.
You can get more details here: https://www.npmjs.com/package/depd
Anyway, if you use express, body-parser is embedded and you do not need to require it. For more details: https://expressjs.com/en/resources/middleware/body-parser.html

All you're doing is calling a function twice. You need to use the "&&" operator to run seperate functions:
var deprecate = require('depd') && require('body-parser')

Related

Is there a reason for using var instead of const in Gulp config files?

According to the answers to this question Const in JavaScript: when to use it and is it necessary? it would make sense to use const for gulpfile.js configuration, would it not?
But in every usage description of gulp-modules, I see var being used like for instance:
var gulp = require('gulp');
var argv = require('yargs').argv;
var autoprefixer = require('gulp-autoprefixer');
//...
As I understand it, these declarations never change while Gulp is running.
Is there a reason for using var? Is it something with node.js compiler? Or is this just a habit?
It's a necessary habit.
gulp is a module and can be used in multiple locations in a code file. But, if you overwrite it accidentally the whole code will crash.
It's better to depend on the computer or compiler. Instead of human accuracy.
If you use const , you can never overwrite the variable. That will avoid error.
I suppose you are not using babel with gulp. If you are using it with babel, it would be better to use const or let instead of var.
If you are not using babel, then var is the only way for you. Read this blog post for further information: https://travismaynard.com/writing/using-babel-with-gulp
Or even better, this https://markgoodyear.com/2015/06/using-es6-with-gulp/

nodejs include required packages in all route files using require() function

Hi I'm new to nodeJs and currently developing a Rest API using node.I'm planning to develop it with a good folder structure, so I can scale it up easily. There I'm using several route files according to the business logic.
ex :- authRoutes,profileRoutes,orderRoutes ......
Currently in every single route file I had to include following codes
var express = require('express');
var router = express.Router();
var jwt = require('jsonwebtoken');
var passport = require('passport');
My problem is , Is it totally fine to use above code segments in all the route files( I'm concerning about the code optimisation/coding standards and execution speed ) or is there any better way to do this.
It's better if you can explain the functionality of require() function.
Thanks
In my experience, this is very standard to do. I suggest reading this question and answer to learn more about the way it affects the speed of your programs.
TL;DR of require()
When your lines of code are ran that include a variable that exists because of a require(), for instance
var https = require('https');
https.get(url, function(response) {...});
The compiler reads it and goes into the https module folder, and looks for the .get function.
However, if you are trying to require() a certain JavaScript file, such as analysis.js, you must navigate to that file from the file you are currently in. For instance, if the file you want is on the same level as the file you are in, you can access it like this:
var analysis = require('./analysis.js');
//Let analysis have a function called analyzeWeather
analysis.analyzeWeather(weather_data);
These lines of code are a little different from above. In this require() statement, we are saying grab the .js file with this name, analysis. Once you require it, you can access any public function inside of that analysis.js file.
Edits
Added require() example for .js file.

Need to call Express like use route using Restify

Expresss.use() accepts 2 parameters
app.use('/abcd', routeHandler);
Restify only supports one
restify.use(routeHandler);
Referring to workaround on https://github.com/restify/node-restify/issues/289
server.use(scopeMiddlewareTo('/prefix', myMiddleware));
I'm trying to use this workaround, but getting below error
{"code":"InternalError","message":"middleware.call is not a function"}
I'm using Typescript, but even the JS code while debugging and middleware.call() is not found.
Basically I have routes in separate files and do not wish to use restify.get(), restify.post() in main.ts. The separate files act as sub-apps.
You can use this package https://www.npmjs.com/package/restify-prefix-route.
var applyPrefix = require('restify-prefix-route');
server.pre(applyPrefix('/v1'));
use this to add prefix in all routes.

NODE JS - TypeError: Path must be a string. Received { request

Hello guys (and girls) ^^
I'm using koa2, koa-router, koa-static (try..) and no koa-send... but nothing work and i need your help. :D
So in fact, my js files are not find...
and i have this ...
So i have installed koa-static and did this:
app.use(serve(__dirname + '/public'));
But a problem like this was appear :
koa deprecated Support for generators will been removed in v3. See the documentation for examples of how to convert old middleware //github.com/koajs/koa/tree/v2.x#old-signature-middleware-v1x server.js:18:5
I don't remember what i've tried but nothing worked... After 3 hours i've decided to change for koa-send !
So i install the new package and i code this from the example...
app.use(async function(ctx){
await serve(ctx, ctx.path, { root: __dirname + '/public' });
});
and now i get ...
TypeError: Path must be a string. Received { request:
Thanks to stackoverflow to lock me with 2 links because of reputation....
so here the code of everything... http://pastebin.com/Gmvg5r9F
Someone have an idea please ? How can i make this functionnal ? I'm desperate... if you have the answer, please... ^_^
And happy new year everyone :p
EDIT : package.json if you need : "http:"//pastebin.com/cBg73WAF
EDIT²: Srsly, i've tried every package and nothing works... My project is actually blocked...
First of all you are getting koa deprecated Support for generators will been removed in v3. See the documentation because you are using a koa v2 with a koa v1 "compatible" middleware but you can easily go around this using koa-convert to convert all generator based middlewares to the new koa v2 async/await standards and use it without a problem.
Example of koa convert
const convert = require('koa-convert');
app.use(convert(serve(__dirname + '/public')));
Lastly, I think you are facing that second error because you are using serve instead of send and that triggers the koa-static you just abandoned instead.

Replacement for req.param() that is deprecated in Express 4

We are migrating from ExpressJS 3 to ExpressJS 4, and we noted that the following APIs are being deprecated:
req.param(fieldName)
req.param(fieldName, defaultValue)
Is there a middleware that brings these APIs back, like other APIs that were 'externalized' from express to independent modules ?
EDITED:
Clarification - The need is an API that provides an abstracted generic access to a parameter, regardless to if it is a path-parameter, a query-string parameter, or a body field.
Based on Express Documentation, we should use like this
On express 3
req.param(fieldName)
On express 4
req.params.fieldName
Personally i prefer req.params.fieldName instead req.param(fieldName)
Why would you want to bring it back? There's a reason that it's been deprecated and as such you should probably move away from it.
The discussion on why they are deprecating the API is available at their issue tracker as #2440.
The function is a quick and dirty way to get a parameter value from either req.params, req.body or req.query. This could of course cause trouble in some cases, which is why they are removing it. See the function for yourself here.
If you are just using the function for url parameters, you can just replace it with this a check for req.query['smth'] or 'default':
var param_old = req.param('test', 'default');
var param_new = req.query['test'] || 'default';
(Please note that an empty string is evaluated to false, so they are not actually 100% equal. What you want is of course up to you, but for the most part it shouldn't matter.)
Ok, after reading the threads given in references by #Ineentho, we decided to come up with the following answer:
https://github.com/osher/request-param
A connect/express middleware to enable back the req.param(name,default) API deprecated in express 4
The middleware does not only brings back the goo'old functionality.
It also lets you customize the order of collections from which params are retrieved , both as default rule, and as per-call :-)
Have fun!

Resources