I am creating a web app with expressjs at the moment.
I want to pass the port that the app is running on from the callingScript to the module:
callingScript.js
const http = require('http');
const app = require('./module');
const port = process.env.PORT || 3000;
app.set('port', port);
const server = http.createServer(app);
// it serves to the correct port, so the problem is passing it to module.js
app.listen(port);
module.js
const express = require('express');
const app = express();
// this always logs `undefined`
console.log(app.get('port'));
module.exports = app;
If I run the above application I want to see results like this:
$ node callingScript.js
3000
$ PORT=8080 bash -c 'node callingScript.js'
8080
but instead it prints undefined every time.
It looks like module.js isn't being passed the variable from its calling script.
How can I pass the port between the two?
You're logging at the wrong time. First your module.js runs, then your callingScript.js runs. The console.log with app.get is in your module.js, which runs before the app.set in callingScript.js.
If you want to do something with the configured port in code in module.js, just ensure you call that code after setting the port. For instance, here we export an object with both app and foo, where foo is a function:
const express = require('express');
const app = express();
module.exports = {
app,
foo: function() {
console.log("The port is " + app.get("port"));
}
};
then calling it:
const http = require('http');
const m = require('./module');
const port = process.env.PORT || 3000;
m.app.set('port', port);
m.foo(); // <====
const server = http.createServer(m.app);
// it serves to the correct port, so the problem is passing it to module.js
m.app.listen(port);
That said, it sounds like you might want to make your module expose a function that accepts a port and returns an app configured to use that port (along with anything else that needs to know what the port is).
Related
I'm new to backend development and I have this following JS code using express
const express = require('express');
const app = express();
const port = process.env.PORT || '3000';
app.listen(port, ()=> console.log(`Listening on port ${port}...`));
I'm trying to change the environment variable process.env.PORT to a different port from the terminal using set PORT=5000 (I'm on windows) but whenever it runs, the value inside env.PORT is always undefined, am I doing something wrong? Also, I'm using VS Code.
In reference to your code example, you want something like this:
var express = require("express");
var app = express();
// sets port 5000 to default or unless otherwise specified in the environment
app.set('port', process.env.PORT || 5000);
app.get('/', function(req, res){
res.send('hello world');
});
// Only works on 3000 regardless of what I set environment port to or how I set
// [value] in app.set('port', [value]).
// app.listen(3000);
app.listen(app.get('port'));
process.env is a reference to your environment, so you have to set the variable there.
SET NODE_ENV=development
I am using below script to run my node app for windows.
SET NODE_ENV=development& node app.js
I need my server to go up, call a function then go down.
From what I've seen on the web I should use this section of code:
const express = require('express');
const app = express();
app.on('listening', () => {
console.log("Server up...");
console.log("Server going down...");
});
but for some reason this does not work for me.
The program does go up but the logs are not written.
const express = require("express");
const app = express();
const server = app.listen(3000);
//call whatever function you need here
server.close(() => console.log("Server going down..."));
First we start the server using app.listen and later when you want to close it just do server.close()
I am writing a RESTful API. IT runs on node.js using the express.js framework, mongodb using mongoose as the object modelling tool & body-parser to pass the http. Everytime I start the server & navigate to the specified IP address, I get a "CANNOT GET/" error. How can I can around this? Some advice would be much appreciated .
I have tired using a different port number but the problem still persists.
Here is a copy of my server.js code:
var express = require('express'),
app = express(),
IP = process.env.IP,
port = process.env.PORT || 8080 ,
mongoose = require('mongoose'),
tasks = require('./api/models/todosModel'),
bodyParser = require('body-parser');
//handiling of promise
mongoose.Promise = global.Promise;
mongoose.connect('mongodb://localhost/Todosdb',{ useNewUrlParser: true });
app.use(bodyParser.urlencoded({extended:true})); // telling the sever instance to use body parser
app.use(bodyParser.json());
var Routes = require('./api/routes/todoRoutes');
//passing the server instance to the routes
Routes(app);
app.listen(port,IP);
console.log("The TODO API server is running on IP: " + IP + " and port: " + port);
The todoRoute code :
'use strict';
module.exports = function(app){
var todofunctions = require('../controllers/todoController');
// todo routes
app.route('/tasks') //task [GET (all the tasks),POST]
.get(todofunctions.listTasks)
.post(todofunctions.createTask);
app.route('/tasks/:taskId') //a task [GET(single task),PUT,DELETE]
.put(todofunctions.updatetask)
.get(todofunctions.readTask)
.delete(todofunctions.deleteTask);
};
It's probably because you have not defined any handler for /.
Try going to the /tasks instead in your browser, then you will get some response.
I have deployed my application (created with npm run build) to heroku. However, the api calls done on heroku production are from my localhost. How do I change this? Could anyone please advice?
api_axios.js
const axios = require('axios')
export default () => {
return axios.create({
baseURL: 'https://myapp.herokuapp.com/api/' || 'http://localhost:1991/api/'
})
}
server.js
const express = require('express')
const bodyParser = require('body-parser')
const cors = require('cors')
const port = process.env.PORT || 1991
// express app
const app = express()
// middleware
app.use(cors())
// routes
const metrics = require('./routes/api/metrics')
app.use('/api/metrics', metrics)
// handle production
if(process.env.NODE_ENV === 'production'){
// static folder
app.use(express.static(__dirname + '/public/'))
// handle spa
app.get(/.*/, (req, res) => res.sendFile(__dirname + '/public/index.html'))
}
// run server
const server = app.listen(port, ()=>{
console.log(`server running on port ${port}`)
})
Just like you check process.env.NODE_ENV in your server, you should also check environment when you compile your JavaScript.
You can use environment variables (via process.env as above), configuration files (such as require('./config.json'), or any other method you like. At the end of the day though, you shouldn't hardcode your API URL.
Started a project with npm which created a certain file structure:
www <-- require() calls app.js; instantiates server
app.js <-- instantiates var app = express(); and has module.exports = app;
Now, I'd like to use sockets.io. In my 'www' file, here is a code snippet:
var app = require('../app');
...
var server = http.createServer(app);
And I'd like to put all of my server-side socket listeners in app.js, but the following code:
var io = require('socket.io').listen(server);
requires server as an input. How do I make the server I instantiated in 'www' accessible in 'app.js'?
It seems a little strange. But if you insist on such a structure than you can export an object from www that will have app as it's property and a method that binds socket listeners an receives app object as a param.
module.exports = {
app: app,
bindSocketListeners: function(server, io) {
io.listen(server);
return io;
}
};
And call it:
var appObj = require('../app');
var io = require('socket.io');
var app = appObj.app;
var server = http.createServer(app);
io = appObj.bindSocketListeners(server, io)