I have one node.js application published in appfog, but when I try to access a mysql database through javascript
with ( https://github.com/felixge/node-mysql ), "node-mysql" seems that is not installed, what is the way to do this?
there is no documentation on appfog site. thanks.
the code of server app.js:
if(process.env.VCAP_SERVICES){
var env = JSON.parse(process.env.VCAP_SERVICES);
var cre = env['mysql-5.1'][0]['credentials'];
}
var Client = require('mysql').Client,
client = new Client();
client.user = cre.user;
client.password = cre.password;
client.host=cre.host;
client.port=cre.port;
client.database=cre.name;
client.connect();
client.query(
'SELECT * FROM scores ',
function selectPlayers(err, results, fields) {
if (err) {
console.log("Error: " + err.message);
throw err;
}
console.log("Number of rows: "+results.length);
console.log(results);
client.end();
});
and the error:
module.js:340
throw err;
^
Error: Cannot find module 'mysql'
at Function.Module._resolveFilename (module.js:338:15)
you should add
"mysql": "2.0.x || 2.1.x",
to the dependencies in your package.json file, and then do
npm install
You can check out Appfog's documentation here. There is a section about dependency management
Appfog have support for NPM, the standard way to install dependencies in node.
You can either do it through the console with npm install mysql or by adding mysql to your package.json file and do npm install.
The second way will automatically install all the dependencies for your app.
Source: https://docs.appfog.com/languages/node#node-dep-mgmt
Hi you just need to download and install node.js locally this will enable npm command on your machine after that go to "Services" section on your AppFog panel create you mySQL service (VCAP_SERVICES)
When you provision and bind a service to your app, AppFog creates an environment variable called VCAP_SERVICES.
This variable contains a JSON document with a list of all credentials and connection information for the bound services.
Here's an example that of the environment variable for an app that has two MySQL database services bound to it:
{"mysql-5.1":[
{
"name":"mysql-4f700",
"label":"mysql-5.1",
"plan":"free",
"tags":["mysql","mysql-5.1","relational"],
"credentials":{
"name":"d6d665aa69817406d8901cd145e05e3c6",
"hostname":"mysql-node01.us-east-1.aws.af.cm",
"host":"mysql-node01.us-east-1.aws.af.cm",
"port":3306,
"user":"uB7CoL4Hxv9Ny",
"username":"uB7CoL4Hxv9Ny",
"password":"pzAx0iaOp2yKB"
}
},
{
"name":"mysql-f1a13",
"label":"mysql-5.1",
"plan":"free",
"tags":["mysql","mysql-5.1","relational"],
"credentials":{
"name":"db777ab9da32047d99dd6cdae3aafebda",
"hostname":"mysql-node01.us-east-1.aws.af.cm",
"host":"mysql-node01.us-east-1.aws.af.cm",
"port":3306,
"user":"uJHApvZF6JBqT",
"username":"uJHApvZF6JBqT",
"password":"p146KmfkqGYmi"
}
}
]}
You can use your app's language-specific facility to call the environment variable.
In Java:
java.lang.System.getenv("VCAP_SERVICES")
In Ruby:
ENV['VCAP_SERVICES']
In Javascript:
process.env.VCAP_SERVICES
In Python:
os.getenv("VCAP_SERVICES")
In PHP:
getenv("VCAP_SERVICES")
Related
I am using the package: https://www.npmjs.com/package/easy-pdf-merge
To merge several PDF files, and it works fine when run from NodeJS.
However when I pack it through Electron-builder I get the following error "Command failed: java -jar" I am guessing it has something to do with Electron-Builder putting node modules into the "app.asar".
I have downloaded Java and added to Path (which means it works fine from CMD)
var merge = require('easy-pdf-merge');
merge(filePaths, 'merged.pdf', function (err) {
if (err) {
console.log('Error: ' + err);
}
resolve('ok');
});
I am not very skilled in either Java or Electron-Builder so any input would be helpful
EDIT:
I have updated code with closing bracket and removed error with opening jar file.
I ended up putting the node module in the app.asar.unpacked folder by modifying package.json with:
"build": {
"asar": true,
"asarUnpack": [
"node_modules/easy-pdf-merge/**/*"
]
},
Afterwards I used the following to reference the node module:
var merge = require(path.join(__dirname, '/../../app.asar.unpacked/node_modules/easy-pdf-merge'));
I'm trying to establish a connection between my Meteor application and my MongoDB Atlas database.
I have the following bit of JavaScript:
var MongoClient = require('mongodb').MongoClient, format = require('util').format;
MongoClient.connect('<MyMongoURL>', function (err, db) {
if (err) {
throw err;
} else {
console.log("successfully connected to the database");
db.collection('largeTreeMap', function(err, docs) {
// Check for error
if(err) return console.log(err);
// Walk through the cursor
docs.find().each(function(err, doc) {
// Check for error
if(err) return console.err;
// Log document
console.log(doc);
})
});
}
db.close(); });
I added this to a blank JS document called test.js and upon running
node test.js
In my command line it returned the success message and data:
So now that I know the connection can be established I added the code to my Meteor project. I created a basic button and onClick the connection to MongoDB should completed.
However, instead I receive the following console error:
I understand from reading various Stack questions that this is a result of not running npm install mongodb in the project directory. However, I have tried doing this and the terminal returns:
Does any body know why the MongoDB is failing to install and preventing me from connecting to MongoDB in my application?
Any help would be much appreciated,
Many thanks,
G
You're trying to connect to the Mongo instance from the client, which is probably not what you want.
The mongodb npm package supports only Node.js, not JavaScript in the browser, as you can see from this line in its package.json
"engines": {
"node": ">=0.10.3"
},
In the case that worked, you are running it with Node.
What you probably want to do is to set the MONGO_URL environment variable to the Mongo Atlas instance, and leave the implementation of connecting / updating to Meteor itself.
I've written a code that should retrieve data from database with nodejs and mysql but it's not working.
It says the I didn't installed the mysql module but I did, using npm install:
The proof that I installed the mysql module successfully:
Is my code ok ? Keep in mind that I'm completely new to node.js.
var http = require('http');
http.createServer(function(request, response){
response.writeHead(200, {'Content-Type': 'text/plain'});
response.write('My first node server...');
var mysql = require('mysql');
var connection = mysql.createConnection({
host : 'localhost:8888',
user : 'root',
password: '',
database: 'test'
});
connection.connect();
connection.query('SELECT * FROM tabel_test', function(err, rows, fields){
if (!err) {
console.log('The result is ', rows);
} else {
console.log('No results.');
}
});
connection.end();
response.end();
}).listen(8888);
The code seems fine, the exception says that you do not have the mysql module, that could be technically true.
Make sure you have the node_modules\mysql folder in the current working directory, or that you have installed it globally with npm install -g mysql.
By the way I suggested the package.json file, because in there you could define the required version of the mysql module. Then if you do npm intall in the folder, the enumerated dependencies will be downloaded to the current working directory. This also make it easier for others to use you code, if you put it into a git repository.
if you found the given path node/node_modules/mysql/lib
change the below line
connection.query('SELECT * FROM test_user', function(err, rows, fields)
connection.end();
I'd like to add a self-updating feature to a globally installed module. Is there a better way of doing it than this?
require("child_process").exec("npm update -g module-name");
There's some documentation about installing npm as a local dependency. Is this necessary? Is there any sample code on how to execute commands like update or install ?
Here's what I've usually done to use the system copy of npm instead of installing another copy of npm as a local module:
function loadNpm(cb) {
require('child_process').exec('npm', function(err, stdout, stderr) {
var m = /npm#[^ ]+ (.+)\n/i.exec(stdout);
if (!m)
return cb(new Error('Unable to find path in npm help message'));
cb(undefined, require(m[1]));
});
}
// usage ...
// only need to call `loadNpm()` once
loadNpm(function(err, npm) {
if (err) throw err;
// load() is required before using npm API
npm.load(function(err, npm) {
if (err) throw err;
// e.g. npm.search('ssh', true, function(err, results) { console.dir(results); });
});
});
Depending on your goals, here are a few options:
1) Via exec() as you mention. Don't forget to add an error callback.
2) Using the npm package as you mention.
For example, I wrote a quick script to install the Yeoman package globally which worked well. I didn't see a lot of documentation for this so I started reading the source code in the npm package itself.
var npm = require('npm');
npm.load (function (err, npm) {
if (err) {
console.log("Error loading");
return;
}
npm.config.set('global', true);
npm.commands.install(['yo'], function (err) {
if (err) {
console.error("Installation failed");
}
});
});
3) Another option is to just have a cron job auto-update packages if that is your goal.
4) You may also be interested in this package https://github.com/tjunnone/npm-check-updates
hi am new to nodejs environment.
am using nodeJs + compoundjs.
am having three database environment development. production and test. my question in when i run the NODE_ENV=production node . command, all url's,port number and other things should get from production.js. when i shift the node environment by giving command NODE_ENV=development node . all things need to run should get from development.js.
any notes for this also helpful for me.
if anybody has any idea please share with me.
You have to set the Environment and then you can configure your app like:
(This is a mongoose db and express, but you can find similar configurations.)
Simply set up three environment configurations
app.configure('development', function () {
mongoose.connect(devConfig.db.path, function onMongooseError(err) {
});
});
app.configure('production', function () {
mongoose.connect(proConfig.db.path, function onMongooseError(err) {
});
});
a configuration example (config.js) :
var config = {};
// Database (MongoDB) configurations
config.db = {
path : 'mongodb://localhost/sampleDatabase'
};
module.exports = config;
I require this file in my app.js by var config = require('config')
You could do the Environment detection in the config file as well.