How do you use a JavaScript function from another file - javascript

So I have a file:
server.js
const express = require("express");
const app = express();
const rateLimit = require("express-rate-limit");
function rateLimiter(request, ms) {}
function startServer(port, dir) {}
And i want to call those two functions in another file
index.js
const express = require("server.js");
var rate = rateLimiter(100, 60000);
var server = startServer(8080, src);
How can I do that?

write something like:
module.exports = {rateLimiter, startServer}

You need to exports those functions and import them to other files.
Here is the export
server.js
const express = require("express");
const app = express();
const rateLimit = require("express-rate-limit");
function rateLimiter(request, ms) {}
function startServer(port, dir) {}
module.exports = {rateLimiter, startServer}
And here is the import
index.js
const express = require("server.js");
const {rateLimiter, startServer} = require('./server.js'); // your server.js file
var rate = rateLimiter(100, 60000);
var server = startServer(8080, src);

Related

Node.js: how to resolve a circular dependency

I know this question has been asked multiple times, but my case is specific:
I have three files, a controller.js, router.js and an app.js,
router.js imports controller.js, app.js imports router.js
I need to import something from app.js to controller.js, how would I do that?
you're probably better off restructuring your code to not need it. Maybe create a third class that uses the other two to accomplish what you need, if you have to use a function in app.js you can do like this:
before requiring you should exports express() and functions
app.js
const express = require("express");
const func = () => {
console.log("I'm in App");
};
var exportFiles = module.exports = {
app: express(),
func: func,
};
var { app } = exportFiles;
const fs = require("fs");
const path = require("path");
const bodyParser = require("body-parser");
app.listen(8080, () => {
console.log("server port is 8080")
})
contolers.js
const {func} = require('../app');
when you call func() in controller result is :
func() // I'm in App

how to export modules that requires other modules

I'm working on a node js project that is getting bigger and bigger, and I'm trying to tidy up my code. This is just a case example.
this is my index.js:
const express = require('express')
const app = express()
const http = require('http').Server(app);
const io = require('socket.io')(http)
io.on('connection', socket => {
socket.on('message', () => doSomething())
})
http.listen(4000, () => console.log('server started'))
and I'd like to import doSomething from another file (say functions.js) like this:
function doSomething(){
console.log(io.sockets.adapter.rooms);
}
module.exports = { doSomething }
modifying index.js as follows:
[...]
const library = require('./functions.js')
[...]
socket.on('message', () => library.doSomething())
but of course:
io is not defined in functions.js.
QUESTION:
How could I import the required modules so that they are shared in both files?
Write your function.js file as below:
function doSomething(){
let self = this;
console.log(self.io.sockets.adapter.rooms);
}
module.exports = function (io) {
let self = this;
self.io = io;
return {
doSomething: doSomething.bind(self)
};
};
And its usage in index.js file will be:
const Library = require('./functions.js');
const library = Library(io);
socket.on('message', () => library.doSomething())
You will have to include the required packages in your functions.js.
Your functions.js should be something like
const io = require('socket.io')(http)
//Include other packages here
function doSomething(){
console.log(io.sockets.adapter.rooms);
}
//Other functions here
//Export all that you need to be exported
module.exports = { doSomething }

How move custom route outside of server.js in jsonServer

In server.js, I am using json-server. I want to move
server.get('/api/1.0/searchDoc', (req, res) => {
const searchType = req.query['searchType'];
const searchValue = req.query['searchValue'];
res.status(200).jsonp({searchType, searchValue});
});
to route.js then import in server.js. How do I achieve it?
Full code
// json server
const jsonServer = require('json-server');
// create server
const server = jsonServer.create();
// data as router
const allDocData = require('../response.json');
const searchDocData = require('../searchResponse.json');
const dataObj = {
'mockResponse': allDocData,
'searchDocData': searchDocData
};
const router = jsonServer.router(dataObj);
// mid-ware
const middlewares = jsonServer.defaults();
// package.json uses port 4000
const port = 4000;
// live before router
// e.g. http://localhost:4000/api/1.0/searchDoc/?searchType='customerId'&searchValue='1234'
server.get('/api/1.0/searchDoc', (req, res) => {
const searchType = req.query['searchType'];
const searchValue = req.query['searchValue'];
res.status(200).jsonp({searchType, searchValue});
});
// use mid-ware
server.use(middlewares);
// use data
server.use(router);
// user body parser
server.use(jsonServer.bodyParser);
// use mid-ware
server.use(middlewares);
// use router
server.use(router);
// listen
server.listen(port);
Do you mean like this? www.js
const JSONServer = require('jsonserver')
function build() {
const server = JSONServer.create()
server.get('/api/1.0/searchDoc', (req, res) => {
const searchType = req.query['searchType'];
const searchValue = req.query['searchValue'];
res.status(200).jsonp({searchType, searchValue});
});
return server
}
module.exports = build
And on another file index.js for example
const build = require('./www.js')
const server = build()
// use mid-ware
server.use(middlewares);
// use data
server.use(router);
// user body parser
server.use(jsonServer.bodyParser);
// use mid-ware
server.use(middlewares);
// use router
server.use(router);
// listen
server.listen(port);
you can if you just return it.
There are a number of ways this could be achieved - another approach would be to inject the server instance into the route.js module which would enable your app's routing concern to be extracted as:
route.js
/*
Define default module function that configures apps routing for the specified
server instance
*/
module.exports = function(server) {
server.get('/api/1.0/searchDoc', (req, res) => {
const searchType = req.query['searchType'];
const searchValue = req.query['searchValue'];
res.status(200).jsonp({searchType, searchValue});
});
}
server.js
const jsonServer = require('json-server');
/*
Import default module function from route.js module. We'll assing this
function to the configureRoutes variable and call it in the server.js when
needed. This import assumes route.js exists in the same directory of this
source file
*/
const configureRoutes = require('./route.js');
const server = jsonServer.create();
const allDocData = require('../response.json');
const searchDocData = require('../searchResponse.json');
const dataObj = {
'mockResponse': allDocData,
'searchDocData': searchDocData
};
const router = jsonServer.router(dataObj);
const middlewares = jsonServer.defaults();
const port = 4000;
/*
Call configureRoutes() to configure routes on your server instance via the
new route.js module
*/
configureRoutes(server);
server.use(middlewares);
server.use(router);
server.use(jsonServer.bodyParser);
server.use(middlewares);
server.use(router);
server.listen(port);

access logger from other js modules

I am just starting in nodejs.
I am instantiating a logger (Pino) in server.js which is the entry point. I only want to create one instance of that logger and use it in other modules.
'use strict';
const express = require('express');
const pino = require('pino');
const log = pino({ level: process.env.LOG_LEVEL || 'info' });
const ping = require('./routes/ping'); //new
const app = express();
app.use('/api/ping', ping);
const port = 3000;
app.listen(port, () => {
console.log(`API server started on ${port}... ^C to end`);
});
module.exports = { app, log }; //edited
So in ping.js how do I get access to log in services.js?
const express = require('express');
const router = express.Router();
const { log } = require('../server'); //edited
router.get('/', async function(req, res) {
log.info('someone pinged');
res.sendStatus(200);
});
module.exports = router;
Edited with suggestions.
You can attach the logger as a property on your app object or on app.locals. Then a reference to it will be accessible through req.app.logger or req.app.locals.logger or whatever in your middlewares and route handlers.
'use strict';
const path = require('path');
const express = require('express');
const ping = require('./routes/ping');
const pino = require('pino');
const log = pino({ level: process.env.LOG_LEVEL || 'info' });
var app = module.exports = express();
app
.use('/api/ping', ping);
const port = config.SERVER_PORT || 3000;
app.listen(port, () => {
console.log(`API server started on ${port}... ^C to end`);
});
module.exports = {app,pino}
Now you can import the same pino instance anywhere.
const log = require('./server.js').pino

How to implement the router(express) inside class constructor in a separate js file

I am trying to do some optimization in a javascript project, I have two files ClassA.js and the appi.js. In the ClassA.js i have the functions that I use for different manipulations and in the api.js I call them via the requests I get. But now I want to move the http methonds inside a javascript class constructor. Like in the following code and I get some errors(and i dont think i got it in the right way, I am a beginner in Nodejs).
Some of the errors are like:
Router.use() requires middleware function but got a Object
And after i made some other changes i get
Json.path is not a function(on my server.js)
//I have imported(required) everything I need, express, router etc..
function classA(filename, jsonparser, url)
{
this.filename = filename;
this.jsonparser = jsonparser;
this.url = url;
router.get(url,function(req,res{classA.prototype.functionA(req,res)});
router.post(url, function(req,res){classA.prototype.functionB(req,res)});
}
classA.prototype.functionA = function(req,res)
{//Does something}
classA.prototype.functionA = function(req,res)
{//Does something}
module.exports = {
router:router,
classA:classA
}
//In the api.js
I want the following
let a = require('../ClasA.js');
let ObjA = new a.classA("filenamepath",JsonObject, "URL");
let express = require('express');
let app = express();
app.use(a.router);
module.exports = router
//Server
const express = require('express');
const bodyParser = require('body-parser');
const path = require('path');
const api = require('./server/routes/api');
const port = 3000;
const app = express();
//Some other code
app.use('/',api);
app.get('*',(req,res)=>{
res.sendfile(path.json(__dirname,'dist/index.html'));
});
//listen function

Categories

Resources