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
Related
I am doing a practise project in Node/Express.
My server.js looks like this:
const express = require("express")
const app = express()
const bodyParser = require("body-parser")
const morgan = require("morgan")
const { get } = require("http")
const PORT = 3000
const budgetRoute = require("./routes/Budget")
const envelopeRoute = require("./routes/Envelopes")
const envelopeNameRoute =require("./routes/Envelopes_name")
const envelopeTransferRoute =require("./routes/Envelopes_transfer")
global.envelopes = []
global.totalBudget = 0
app.use(bodyParser.json())
app.use(morgan("dev"))
app.use("/envelopes", envelopeRoute)
app.use("/envelopes/:name", envelopeNameRoute)
app.use("/envelopes/transfer/:name", envelopeTransferRoute)
app.use("/budget", budgetRoute)
app.listen(PORT, () =>{
console.log(`Listening on port ${PORT}`)
})
now in my Route file routes/Envelopes_name I have this:
router.put("/", (req,res,next)=>{
const envelopeToChangeName = req.params.name
const envelopeName = req.query.name
const envelopeBudget = req.query.budget
const reqEnvelope = envelopes.find(envelope => envelopeToChangeName)
if(envelopeBudget){
reqEnvelope.budget = envelopeBudget
}
if(envelopeName){
reqEnvelope.name = envelopeName
}
res.status(201).send(reqEnvelope)
})
after sending request localhost:3000/envelopes/groceries?name=taxes it should change the name of the envelope from "groceries" to "taxes". For some reason req.params.name is "undefined" and I have error "TypeError: Cannot set properties of undefined (setting 'name')". When I had it all in one file, without routers, it worked perfectly. Any ideas?
I think you need to add { mergeParams: true } to make the params available, because you use another router file then where you define the route.
See Express docs
In this fictive project I am trying to set up the Routing structure. Although I used module.exports in both files, running a test still gives me the following error:
TypeError: Router.use() requires a middleware function but got a Object
My Code:
Minions.js
const minionsRouter = require('express').Router();
module.exports = minionsRouter;
const {
getAllFromDatabase,
addToDatabase,
getFromDatabaseById,
updateInstanceInDatabase,
deleteFromDatabasebyId,
} = require('./db.js');
minionsRouter.get('/', (req, res, next) => {
const minionsArray = getAllFromDatabase('minions');
if (minionsArray) {
res.status(200).send(minionsArray);
} else {
res.status(404).send();
}
});
API.js
const express = require('express');
const apiRouter = express.Router();
const minionsRouter = require('./minions');
const ideasRouter = require('./ideas');
const meetingsRouter = require('./meetings');
apiRouter.use('/minions', minionsRouter);
apiRouter.use('/ideas', ideasRouter);
apiRouter.use('/meetings', meetingsRouter);
module.exports = apiRouter;
Server.js
const express = require('express');
const app = express();
module.exports = app;
/* Do not change the following line! It is required for testing and allowing
* the frontend application to interact as planned with the api server
*/
const PORT = process.env.PORT || 4001;
// Add middleware for handling CORS requests from index.html
const cors = require('cors');
app.use(cors());
// Add middleware for parsing request bodies here:
const bodyParser = require('body-parser');
app.use(bodyParser.json());
// Mount your existing apiRouter below at the '/api' path.
const apiRouter = require('./server/api');
app.use('/api', apiRouter);
// This conditional is here for testing purposes:
if (!module.parent) {
// Add your code to start the server listening at PORT below:
app.listen(PORT, () => {
console.log(`Server is listening on port ${PORT}`)
})
};
Any help is much appreciated!
I'm structuring my code to become more readable and maintainable at the same time.
here is my GET.articles and my INSERT.articles is just the same with this.
const express = require('express');
const router = express.Router();
router.get('/sample', (req, res) => {
res.send("Nice")
})
module.exports = router;
my index.js
const GET_articles = require('./GET.articles');
const INSERT_articles = require('./INSERT.articles');
exports { GET_articles, INSERT_articles}
and I import it like this:
app.use('/example', require('./routes/articles_controller/index'));
This is my error:
SyntaxError: Unexpected token export
Look at your first block of code:
module.exports = router;
Do that.
Change:
exports { GET_articles, INSERT_articles}
to
module.exports = { GET_articles, INSERT_articles}
If you want to use import and export then see this question.
Then note that a plain object isn't something you can just use.
You should use the routers and not the object containing them.
const routers = require('./routes/articles_controller/index');
app.use('/example', routers.GET_articles);
app.use('/example', routers.INSERT_articles);
app.js file
const express = require('express');
const router = express.Router();
const exampleRoute = require('./routes/articles_controller/index');
var app = express();
app.use('/', router)
app.use('/example', router, exampleRoute);
router.get('/sample', (req, res) => {
res.send("Nice")
})
app.listen(3000, ()=>{
console.log("Listening on port 3000")
})
route file
const GET_articles = require('./GET.articles');
const INSERT_articles = require('./INSERT.articles');
module.exports = [GET_articles, INSERT_articles]
GET articles files
module.exports = function getArticle (req, res) {
//Logic as required goes here
res.send("Content to be rendered")
}
I am trying to export the middleware function so that other classes can call it.
I did some google search but did not work for my case.
Here is the code
auth.js
isLoggedIn = (req, res, next) => {
next();
}
module.exports.isLoggedIn = isLoggedIn;
module.exports = app => {
};
profile.js
const isLoggedIn = require('./auth').isLoggedIn;
let profile = [];
getAllProfile = (req, res) => {
res.send(profile);
}
module.exports = (app) => {
app.get('/all-profile',isLoggedIn, getAllProfile);
}
index.js
const express = require("express");
const bodyParser = require("body-parser");
const app = express();
app.use(bodyParser.json());
const port = process.env.PORT || 3000;
const server = app.listen(port, () => {
const addr = server.address();
console.log(`Server listening at ${port}`);
});
let auth = require("./src/auth");
auth(app);
let profile = require("./src/profile");
profile(app);
The error message is
\node_modules\express\lib\router\route.js:202
throw new Error(msg);
^
Error: Route.get() requires a callback function but got a [object Undefined]
What am I doing wrong here?
You are overwriting your module.exports with the second line here:
module.exports.isLoggedIn = isLoggedIn;
module.exports = app => {
};
So .isLoggedIn is no longer a property of the new exports object you assigned. You could flip the order:
module.exports = app => {
};
module.exports.isLoggedIn = isLoggedIn;
That way, you define a new module.exports object first (which happens to be a function object) and then add a property to the new object.
I have a file on main root as
test_file.js
Following is the code inside it
var config = require('config');
var Ctrl = require('./Controllers');
var port = process.env.PORT || config.get("PORT") || 3000;
var cors = require('cors');
var express = require('express');
var app = express();
var router = express.Router();
app.use(cors());
app.use(router);
var server = require('http').createServer(app);
var io = require('socket.io')(server, {'pingInterval': 4000, 'pingTimeout': 6000});
io.on('connection', Ctrl.connection);
console.log("Opening at port " + port);
server.listen(port, function () {
});
module.exports = router;
require('./Routes')();
I have another file in path
/Controllers/index.js
i want to pass out io to index.js too, here is its code
var Promise = require('q').Promise;
var config = require('config');
var mysql = require('mysql');
/// I want to get var io = require('../test_file.js');
/**Initialization socket connection */
exports.connection = function (socket) {
if (!(socket.handshake.query.accountType != null && socket.handshake.query.id != null && socket.handshake.query.accessKey != null
&& socket.handshake.query.id > 0)) {
socket.disconnect();
return;
}
Now i am confused about module.exports and exports, my module.exports is already passing out to another file, i want to add another variable i-e io and pass it to controllers file. How can i do that
In respond to the query,
app.use(router);
var server = require('http').createServer(app);
var io = require('socket.io')(server, {'pingInterval': 4000, 'pingTimeout': 6000});
module.exports = {
router: router,
io: io
};
io.on('connection', Ctrl.connection);
console.log("Opening at port " + port);
server.listen(port, function () {
});
require('./Routes')();
In Controllers/index.js
var Promise = require('q').Promise;
var config = require('config');
var mysql = require('mysql');
var Driver = require('./driver');
var User = require('./user');
var io = require('../test_file.js').io;
console.log("logging");
console.log(io);
the result is {} for io
exports is just module.exports's little helper. Your module returns module.exports to the caller ultimately, not exports. All exports does is collect properties and attach them to module.exports IF module.exports doesn't have something on it already. If there's something attached to module.exports already, everything on exports is ignored.
you can pass both as the object
module.exports = {
router: router,
io: io
};
Please refer this doc for more explanation
Edit
Access object via module.exports
file.js
var express = require('express');
var router = express.Router();
/* GET users listing. */
router.get('/', function(req, res, next) {
res.send('respond with a resource');
});
module.exports = {router:router};
Acess it with
var router=require('./file').router
OR
var router=require('./file');
router.router