It is a very small issue but I can't find out: I have 2 file in the same folder: config.js and server.js. The last one uses the config.js with the following code:
...
var config = ('./config');
...
//Configuration
var port = process.env.PORT || 8080;
mongoose.connect(config.database);
By running the server I have problem with connection due to a wrong address, infact the following error is shown
MongoError: failed to connect to server [undefined:27017] on first connect ...
The config.js contains just:
module.exports = {
'secret' : 'test123',
'database' : 'mongodb://127.0.0.1:27017/test'
};
And If I replace the mongoose.connect with the following code
mongoose.connect('mongodb://127.0.0.1:27017/test');
everything works fine... Why it can't resolve the database name?
You must to use var config = require(./config.js) and config.js must be on the same dir if you do that, the problem is you forgot require
Related
Im am trying to load images in phaser with node js and i always get the same error
:3000/assets/img/feet/idle/survivor-idle_0.png:1 Failed to load resource: the server responded with a status of 404 (Not Found)
if you know a way to get this to work please tell me. here is my code:
preload() {
// Used for preloading assets into your scene
//Idle feet image
this.load.image('idleFeetFrame', '/assets/img/feet/idle/survivor-idle_0.png');
}
(Updated from Comment)
... is my server code:
const express = require('express');
const app = express();
const server = app.listen(process.env.PORT || 3000);
app.use(express.static('./public'));
console.clear();
console.log('\x1b[36m%s\x1b[0m', 'Server started...\n');
const socket = require('socket.io');
const io = socket(server);
io.sockets.on('connection', handleConnection);
function handleConnection(socket) { console.log('Client: ' + socket.id + ' has connected.') }
Since there are not any special routes configured in express, I assume all your files are in the folder ./public.
In that case the file survivor-idle_0.png would have to be in the folder ./public/assets/img/feet/idle/survivor-idle_0.png if you can't find it in that path, that is the problem (check for typos, or extra folder like src).
As long as you are not using a bundler like webpack, parcel or so, just need to check your the public folder and fix the paths.
If you are using a bundler, you will have to check the bundler configuration for errors.
I'm trying to add Log4js-Node to a Node.js server running on Apache. Here's my code:
const path = require("path");
const express = require("express");
const log4js = require('log4js');
const app = express();
const logger = log4js.getLogger();
logger.level = "debug";
const port = 443;
log4js.configure({
appenders: { everything: { type: 'file', filename: 'logs.log', flags: 'w' } },
categories: { default: { appenders: ['everything'], level: 'ALL' } }
});
const server = app.listen(port, () => {
logger.debug("listening to requests on port " + port);
});
app.get("/log", (req, res) => {
res.sendFile(path.join(__dirname + "/logs.log"));
});
When I run the script on Node.js on my computer and navigate to localhost:443/log I see what I expect, which is this:
[2020-03-17T22:50:43.145] [DEBUG] default - listening to requests on port 443
But when I run the code on a remote server it crashes and I get this in the error page (with part of the path replaced by me with "[removed]"):
App 25925 output: at Server. ([removed]/index.js:27:9)
App 25925 output: at Logger. [as debug] ([removed]/12/lib/node_modules/log4js/lib/logger.js:124:10)
App 25925 output: at Logger.log ([removed]/12/lib/node_modules/log4js/lib/logger.js:73:12)
App 25925 output: at Logger._log ([removed]/12/lib/node_modules/log4js/lib/logger.js:90:16)
App 25925 output: at Object.send ([removed]/12/lib/node_modules/log4js/lib/clustering.js:97:15)
App 25925 output: [removed]/12/lib/node_modules/log4js/lib/clustering.js:97
App 25925 output: at Object. ([removed]/12/lib/node_modules/log4js/lib/clustering.js:8:13)
I'm using A2 Hosting which uses Apache 2.4.41. I opted for Node.js 12.9.0, and Log4js 6.1.2. The package.json should be the same on both my computer and the server, and I've run npm install on both.
Is this just an issue with Log4js and the server, or have I missed something somewhere?
This was actually a relatively simple fix. The path referenced by the last error in the stack trace is a Log4js module that implements clustering support through Node's "cluster" module. The line "8" referenced is cluster = require("cluster"). It's wrapped in a try/catch block like this:
try {
cluster = require("cluster"); //eslint-disable-line
} catch (e) {
debug("cluster module not present");
disabled = true;
}
The installation of Node.js on my computer came with the "cluster" module, however as far as I can tell, the server I'm using doesn't support it. Also, the version of Node I'm using on my computer is newer than what I'm using on the server (so I've now installed 12.9 on my machine). I believe the older version of Node doesn't bother trying to catch the exception and tries to load the cluster module, fails, and then throws the error.
So the simple fix was to comment out most of the "try/catch" block, leaving just the contents of "catch" like this:
// try {
// cluster = require("cluster"); //eslint-disable-line
// } catch (e) {
debug("cluster module not present");
disabled = true;
// }
If someone has a better fix, I'm open to suggestions.
The same response of #skittleswrapper,thx, it work for me.
I use Node.js 14.18.1 with log4js 6.3.0.
But i wondering what'is the necessary of this module 'cluster' and if we can
add it to our app in other way.
How do I use socket.io with browserify?
When socket.io is installed in a node app, it creates this url path for ths socket.io script:
/socket.io/socket.io.js
But what would be the real path of that file (relative to the node_modules dir) which needs to be passed to browserify?
Is it e.g.
socket.io-client/socket.io.js
or maybe
socket.io/lib/client.js
In the documentation of socket.io-client it says "Socket.IO is compatible with browserify." But they don't say how.
If you struggled to get it working with browserify as a window global use this code for the integration:
var io = require('socket.io-client');
window.io = io;
Here's a minimal client:
// client.js
var socket = require('socket.io-client')();
socket.on('message', ...);
Which you can Browserify:
browserify client.js > bundle.js
The path will be exactly the same since it's the server who serve the socket.io client library (and I guess you're not browserifying the server, are you?).
But I use a more convenient solution: check this out.
io = require 'socket.io-client'
class Network
constructor: (game, refresh_infos) ->
#sock = io()
#...
pending: (name, cb) ->
#name = name
#sock.emit 'pending', name: name
#sock.on 'new_game', (data) => cb data
Abrakadabra!
Import client and then assign it to variable with:
var client = require('socket.io/lib/client');
You can then call client.
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.
When I run my application locally, everything works as expected, but when I deployed it to cloudno.de , it looks like this.
I get an error Uncaught SyntaxError: Unexpected token < which is because the contents of greeting.js is
<!doctype html>
<html lang="en">
.......
Obivously not my javascript-file, but infact the contents of my index.html
My project is barely started and its using a Backbone Boilerplate, the code in its entirety can be viewed here.
Does anyone know what could possibly be the reason for this?
My server.js:
// Require libraries
var fs = require("fs");
var express = require("express");
var site = express.createServer();
// Determine which dist directory to use
var dir = process.argv.length > 2 && "./dist/" + process.argv[2];
// Use custom JS folder based off debug or release
dir && site.use("/assets/js", express.static(dir + "/js"));
dir && site.use("/assets/css", express.static(dir + "/css"));
// Serve static files
site.use("/app", express.static("./app"));
site.use("/assets", express.static("./assets"));
site.use("/dist", express.static("./dist"));
// Ensure all routes go home, client side app..
site.get("*", function(req, res) {
fs.createReadStream("./index.html").pipe(res);
});
site.listen(8000);
console.log("Server listening on http://localhost:8000");
Do you copied and pasted this code? there did you get the var dir = process.argv... line?
The error could be due to the cloudno.de being initialized without arguments. Your app is looking for them on process.arv