Im using node with express and when I create server im listening to port 3000
in app.js by code,my question if there is any way to define it (host &port ) from exteranl file like some config json or something.if I want to be able to provide it from file .
You can "require" a config.
your config.json (can be js too).
{
"environment": "development",
"other": "value"
}
in app.js:
var cfg = require('./config.json');
Now you can access cfg properties.
Create config file, config.json:
{
"host": "localhost",
"port": 3000
}
Use require() to read it:
var express = require('express');
var app = express();
var config = require("./config.json");
app.listen(config.port, config.host, ...
Related
Yesterday, I had dotenv installed and referenced, and the Server was calling on port 4000 through env, I had Postman working and referencing the server but that stopped when I started my coding today, I have no idea what I changed, because I didn't think I had done anything.
My .env file is below:
PORT = 4000
NODE_ENV = DEVELOPMENT
DB_URI = mongodb+srv://<xxx>:<xxx>#products.<xxx>.mongodb.net/?retryWrites=true&w=majority`
My server.js file is below:
const app = require ('./app');
const connectDatabase = require('./config/database');
const dotenv = require ('dotenv')
//I'm switching between these two PORT constants to debug
const PORT = process.env.PORT
const PORT = 4000
const URI = process.env.URI
// environment variable setup (tutorial runs server through the root, hence the backend/...).
dotenv.config({ path: 'backend/config/config.env'});
// DB connection
connectDatabase();
app.listen(PORT, () => {
console.log(`Server running on PORT: ${PORT} as a ${process.env.NODE_ENV} project`);
});
When I run with the port number called directly through server.js the port loads as 4000:
But when I run through the environment variables I get undefined:
Not that it matters, but I turned off my VPN and restarted it. Not sure why it makes the error now.
On your server.js file, you are defining the PORT const using the process.env.PORT before calling dotenv.config(), because of that you env vars are not defined yet.
Try change your code to:
dotenv.config({ path: 'backend/config/config.env'});
const PORT = process.env.PORT || 4000;
const URI = process.env.URI;
I am working on a react application that takes the json file path as a parameter to render the json data in my ui. Accessing local files from the browser is restricted, so how can I create a backend server to retrieve my local json files and serve them to the browser?
you can boot up a local server using express, and use the fs module to access file content
const fs = require('fs');
const file_content = fs.readFileSync('./{file_name}',
'{content_formate}').toString();
// For show the data on console
console.log(file_content);
To create a server that is listening on port 3000, use
const express = require('express')
const fs = require('fs');
const app = express()
const port = 3000
app.get('/', (req, res) => {
const file_content = fs.readFileSync('./{file_name}',
'{content_formate}').toString();
res.send(file_content)
})
app.listen(port, () => {
console.log(`Example app listening at http://localhost:${port}`)
})
something like this
To access local json files in your swagger application, you need to use express - as the browser cannot access your local file system. You can create an endpoint, i.e. '/swagger', that will allow you to serve the files from the directory provided. In the urls parameter, you will use '/swagger/name.json', rather than the local path. Create a driver.js file with the following content:
var express = require('express');
var app = express();
app.use('/swagger', express.static('/path/to/local/files'));
app.listen(3000);
I am currently working on a nodejs project, and I have a simple question. I want to serve some libraries from my node_modules folder statically to the client (maybe stupid, but not relevant to the question), but I dont want to trash my main server JS file with all these statically served files like this:
const express = require('express');
const app = express();
// Imports here
app.use('/assets/lib/bootstrap', './node_modules/bootstrap/dist');
app.use('/assets/lib/axios', './node_modules/axios/dist');
app.use('/assets/lib/aos', './node_modules/aos/dist');
app.listen(3000, () => {
console.log('Server listening on port 3000');
});
If I have 10+ imports, this would trash up my Server JS file, which I like to keep as clean as possible. I was wondering why this option wouldn't work:
./routes/route1.js :
const express = require('express');
const router = express.Router();
const path = require('path');
// Imports here
router.use('/bootstrap', path.resolve(__dirname, 'node_modules/aos/dist'));
router.use('/axios', path.resolve(__dirname, 'node_modules/aos/dist'));
router.use('/aos', path.resolve(__dirname, 'node_modules/aos/dist'));
// path to node_modules file is not the problem here
module.exports = router
And in my main Server JS file:
const express = require('express');
const app = express();
const route1 = require('./routes/route1');
// Imports here
app.use('/assets/lib', route1);
app.listen(3000, () => {
console.log('Server listening on port 3000');
});
But this gives me an error. The file is not statically served to the client. Is this because an express Router can't serve static files? Maybe this is a rookie mistake, but any help is appreciated. The first code snippet does work, but I'm trying to keep my code organized.
Use the express.static middleware in your route1.js file instead of simply passing the folder path string to the route.
I'm creating an online multiplayer .io game similar to https://diep.io/ or https://agar.io/ and I'm in the process of setting up a server this is my code,
var path = require('path');
var http = require('http');
var express = require('express');
var socketIO = require('socket.io');
var publicPath = path.join(__dirname, '../client');
var port = process.env.PORT || 2000;
var app = express();
var server = http.createServer(app);
var io = socketIO(server);
app.use(express.static(publicPath));
server.listen(port, function () {
console.log('Server stared on port ' + port);
});
When I start the server and put "localhost:2000" into the search bar this is what comes up,
I'm kinda new to this so if you could make the answers simple to understand then I'd really appreciate it.
Double check your paths. Your code will work as written if you have a folder structure like so:
/server/index.js
/client/index.html
$ node server/index.js
The static middleware by default will serve files which match html, html.
So if you have index.html, you can make a request to /, and if you have hello.html, you can hit it at /hello.
See here for more options: http://expressjs.com/en/resources/middleware/serve-static.html
Note: this middleware is what Express.static uses, so no need to install that package, just look at examples for serveStatic() and pass those to Express' version.
What would be the best way to store DB config (username, password) in an open source app that runs on node.js / Express? Two specific questions:
Shall I put it into a separate config.js file in /lib folder, for example, and never include it into the master repository that is publicly available on GitHub?
To inlcude the config, is it as simple as require('./config.js') from the file that needs it or is there a better way of doing it?
PS sorry if the questions seem a bit simple or not so well formulated, but I'm just starting :)
Here's how I do it:
Create a config.js which contains objects representing your configs:
var config = {
development: {
//url to be used in link generation
url: 'http://my.site.com',
//mongodb connection settings
database: {
host: '127.0.0.1',
port: '27017',
db: 'site_dev'
},
//server details
server: {
host: '127.0.0.1',
port: '3422'
}
},
production: {
//url to be used in link generation
url: 'http://my.site.com',
//mongodb connection settings
database: {
host: '127.0.0.1',
port: '27017',
db: 'site'
},
//server details
server: {
host: '127.0.0.1',
port: '3421'
}
}
};
module.exports = config;
Then in my index.js (or wherever really),
var env = process.env.NODE_ENV || 'development';
var config = require('./config')[env];
Then process with that object, e.g.
var server = express();
server.listen(config.server.port);
...
For running toy apps where I need to hide db credentials, I use the dotenv module.
Place your sensitive info in a .env file (which is .gitignored), place require('dotenv').config(); in your app; dotenv creates entries in process.env that you can refer to.
.env file:
DATABASE_PASSWORD=mypw
DATABASE_NAME=some_db
To refer to the values:
process.env.DATABASE_PASSWORD
Not sure whether this is the best practice, but personally I have a config.json file where I store my db connection information. Then I do the following:
// options.js
var fs = require('fs'),
configPath = './config.json';
var parsed = JSON.parse(fs.readFileSync(configPath, 'UTF-8'));
exports.storageConfig= parsed;
Then from a different file I do the following:
var options = require('./options');
var loginData = {
host: options.storageConfig.HOST,
user: options.storageConfig.user,
password: options.storageConfig.password
};
I do put in args. just like the port of so many node.js example.
you most likely forever, pm2, nodemon to run your app. so this variable is not check in as part of your source code. and they are globally available too.
process.env.PORT
process.env.DATABASE_USER
process.env.DATABASE_PASSWORD
PORT=3000 DATABASE_HOST=localhost DATABASE_USER=admin DATABASE_PASSWORD=mypassword node app.js
export PORT=3000
export DATABASE_HOST=localhost
export DATABASE_PORT=27017
export DATABASE_USER=admin
export DATABASE_PASSWORD=mypassword
node app.js
var server = app.listen(process.env.PORT, function() {
});
var mongoClient = new MongoClient(new Server(process.env.DATABASE_HOST, process.env.DATABASE_PORT));
To inlcude the config, is it as simple as require('./config.js') from the file that needs it or is there a better way of doing it?
This is the right way to store config files.
The best approach would be to write your entire application like an ordinary node.js module, and write a small start-up file that calls it. This idea also allow you to use different database drivers using dependency injection.
Good, but not perfect solution is the environment. It is shared among all application, so if you have certain data you want to be available to all of them, this is the best bet. But if you have a config for one particular app, not much so.
PS: And please, don't use JSON for this. It's the worst idea possible. :)
I found this a nice way to handle my config, considering different environments:
config.coffee
exports.setEnvironment = (env) ->
switch env
when "development"
exports.DEBUG_LOG = true
exports.DB_PORT = '27017'
# ...
when "testing"
exports.DEBUG_ERROR = true
exports.DEBUG_CLIENT = true
# ...
when "production"
exports.DEBUG_LOG = false
# ...
else console.log "environment #{env} not found"
server.coffee:
config = require('./config')
config.setEnvironment env
Using environment variables
You can use export to set environment variables in OSX and Linux. The following is an example of setting a value in the SESSION_SECRET key.
export SESSION_SECRET="keyboard cat"
In Windows, you can use set.
set SESSION_SECRET="keyboard cat"
You can also set environment variables each time you run them.
SESSION_SECRET="keyboard cat" node secret-env.js
Use process.env of node.js to access environmental variables within code.
var express = require('express')
var session = require('express-session')
var app = express()
app.use(session({secret: process.env.SESSION_SECRET}))
Request a argument from the command-line
The best way to protect confidential information is not to store it in a setup file.
If the command-line requests configuration information as an argument using the noopt package, the secret information does not need to exist as a file.
The following is an example of requesting a session key as an argument using the noopt package.
var nopt = require("nopt")
var longOpts = {
"sessionSecret": String,
}
var shortOpts = {
"s": ["--sessionSecret"],
}
var parsed = nopt(longOpts, shortOpts, process.argv, 2)
console.log("session secret is:", parsed.sessionSecret)
node secret-arg.js --sessionSecret "keyboard cat"
node secret-arg.js -s "keyboard cat"
Advantages : It is safer to expose confidential information than to hardcoding or having it as a configuration file.
Disadvantages : There is a hassle of increasing the amount of information to be entered each time the app is launched.
If you try to create and solve a script, the problem that the password still exists in the script remains.