var PersonalityInsightsV2 = require('watson-developer-cloud/personality-insights/v2');
var personality_insights = new PersonalityInsightsV2({
username: '<username>',
password: '<password>'
});
personality_insights.profile({
text: '<?php echo $_Session['description'];?>',
language: 'en' },
function (err, response) {
if (err)
console.log('error:', err);
else
console.log(JSON.stringify(response, null, 2));
});
It doesn't display anything. I have also done npm watson cloud and saved it, I have put my credentials and also forked it on git. What am I missing? I am a beginner but would love to use this on my page!
Here are the steps to run it locally, since you are a beginner I'll start from the beginning.
Create a new folder and name it whatever you want. Put these files in there.
Name the first file: index.js
fill in <YOUR-USERNAME>, <YOUR-PASSWORD>, and <YOUR-100-UNIQUE-WORDS> variables.
var express = require('express');
var app = express();
var http = require('http').Server(app);
var cfenv = require("cfenv");
var appEnv = cfenv.getAppEnv();
http.listen(appEnv.port, appEnv.bind);
var PersonalityInsightsV2 = require('watson-developer-cloud/personality-insights/v2');
var personality_insights = new PersonalityInsightsV2({
username: '<YOUR-USERNAME>',
password: '<YOUR-PASSWORD>'
});
personality_insights.profile({
text: "<YOUR-100-UNIQUE-WORDS>",
language: 'en' },
function (err, response) {
if (err)
console.log('error:', err);
else
console.log(JSON.stringify(response, null, 2));
});
Create another file and name it: package.json
put these contents in there
{
"name": "myWatsonApp",
"version": "1.0.0",
"description": "A Watson Personality Insights application",
"main": "index.js",
"scripts": {
"start": "node index.js"
},
"dependencies": {
"cfenv": "^1.0.3",
"express": "^4.13.4",
"watson-developer-cloud": "^2.2.0"
}
}
open your terminal and cd to the root of your folder you just created.
Run the command: npm install
Then run the command npm start
Your application will then be running and you will see output from the personality insights call you made in index.js
Related
Basically, ive got start:"nodemon node.js" node.js is the actual file. but all it does is bring it up in my editor and port 3000 still isnt responding like it would if i typed node node.js every time i edited it. i did everything in the tutorial verbatim looked up the actual docs and searched stack and im still at a stand still, i am new to this and could use some help please,i installed it npm install nodemon --save-dev and would like to be able to do this in the local environment if possible, the modules are there, its just alot to past here, thanks in advance heres my code and such...
edit: when i run it i get
nod#1.0.0 start
nodemon node.js
in the terminal
const http = require('http');
const fs = require('fs');
const server = http.createServer((req,resp)=>{
const url = req.url;
const method = req.method;
{
"name": "nod",
"version": "1.0.0",
"description": "",
"main": "node.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1",
"start": "nodemon node.js"
},
"author": "",
"license": "ISC",
"devDependencies": {
"nodemon": "^2.0.15"
}
}
//.........................................................................................
if(url === '/'){
resp.write('<html>');
resp.write('<head><title>first</title></head>')
resp.write('<body>');
resp.write('<form action="/message"npmns npmno method="POST"><input type="text" name="message"><button type="submit">subn</button></form>');
resp.write('</body>');
resp.write('</html');
return resp.end();
}
if(url === '/message' && method=== 'POST'){
// resp.write('<html>');
// resp.write('<body');
const body =[];
req.on('data',(chunk)=>{
body.push(chunk);
})
req.on('end',(data)=> {
let message = body.toString().split('=')[1];
fs.writeFileSync('billy.txt', message);
})
resp.write('<form action="/" method="POST"><button type="submit">butt</button></form>');
// resp.write('</body>');
// resp.write('</html>');
return resp.end();
}
resp.setHeader('content-type','text/html');
resp.write('<html>');
resp.write('<head><title>firsttime</title></head>');
resp.write('<body><h1>hello again</h1></body>');
resp.write('</html>');
resp.end();
})
server.listen(3000);
i am trying to connect mssql database but i couldnt achieve that.
When i connect mssql on Microsoft SQL Server Management Studio 18;
https://i.stack.imgur.com/6xdI0.png -- Because of Windows Authentication, i have no password. And there is a username field passive as default, also node js doesnt accept default user name. Why? and what i am doing wrong? When i try to execute js file; https://i.stack.imgur.com/Ty0zA.png -- gives an user name error in cmd db.js file;
var sql = require('mssql');
// config for your database
var config = {
user: 'DESKTOP-S9H932R\\CUNEYT',
password: '',
server: 'localhost',
database: 'cuneyt'
};
// connect to your database
sql.connect(config, function (err) {
if (err) console.log(err);
// create Request object
var request = new sql.Request();
// query to the database and get the records
request.query('select * from borsa', function (err, recordset) {
if (err) console.log(err)
// send records as a response
res.send(recordset);
});
});
package.json file;
{
"name": "mssql_test",
"version": "1.0.0",
"description": "",
"main": "db.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"keywords": [],
"author": "",
"license": "ISC",
"dependencies": {
"mssql": "^6.3.1"
}
}
OP solved but for anyone having trouble my issue was that I was connecting to a local DB within a domain. I had to add the option to my config object to be like
config:{
user:'xxxx',
password:'xxxx',
server:'servername',
database:'yourdb'
domain:'yourdomainname'}
I would like to deploy a Node.JS app on Cloud Foundry.
I follow the following steps:
Add the engines part in the package.json
{
"name": "vsapc",
"version": "1.0.0",
"description": "Application Name",
"main": "server/app.js",
"scripts": {
"start": "node server/app.js",
"backup": "node backup.js",
"restore": "node restore.js",
"seed": "node server/seed/Seed.js",
"postinstall": "node install.js"
},
"directories": {
"test": "test"
},
"dependencies": {
"bcrypt-nodejs": "0.0.3",
"body-parser": "^1.15.2",
"cfenv": "^1.0.3",
"express": "^4.14.0",
"jsonwebtoken": "^7.1.9",
"mongodb": "^2.2.5",
"mongoose": "^4.6.3",
"mongoose-seed": "^0.3.1",
"morgan": "^1.7.0",
"promise": "^7.1.1",
"prompt": "^1.0.0",
"winston": "^2.2.0",
"winston-daily-rotate-file": "^1.4.0"
},
"engines": {
"node": "6.11.*",
"npm": "5.*"
},
"author": "",
"license": "ISC"
}
I create the manifest.yml
---
applications:
- name: Policy_Studio
memory: 2048MB
env:
NODE_ENV: production
I used the following to connect in install.js:
const vcapServices = JSON.parse(process.env.VCAP_SERVICES);
let mongoUrl = '';
mongoUrl = vcapServices.mongodb[0].credentials.uri;
mongoose.connect(mongoUrl,{useMongoClient: true}, function (err){
if (err) {
console.log("Database connection responded with: " + err.message);
console.log("Is your server.config.json up to date?");
process.exit(1);
return
}
console.log("Connected to database.");
and the following in app.js:
Server.prototype.connectDatabase = function (url) {
mongoose.Promise = Promise;
const vcapServices = JSON.parse(process.env.VCAP_SERVICES);
let mongoUrl = '';
mongoUrl = vcapServices.mongodb[0].credentials.uri;
mongoose.connect(mongoUrl,{useMongoClient: true});
mongoose.connection.on("error", function (err) {
log.error(err)
});
mongoose.connection.once("openUri", function () {
log.info("Connected to DB")
})
};
connect by command line to SCAPP and push the app with cf push
As i don't have the MongoDB on the cloud i have an error
I build a MOngoDB service on the cloud and bind directly the app through the web GUI
On the gui i click restage button for my app
I have the error
Database connection responded with: failed to connect to server
[2xtorvw9ys7tg9pc.service.consul:49642] on first connect [MongoError:
connect ECONNREFUSED 10.98.250.54:49642]
I add the service mongoDB in my manifest and cf push my application
Still the same error as in point 9
I tried to change the connection in install.js
Thank you for your help
While your parsing of VCAP_SERVICES appears to work (you get a URL containing a hostname & port), i highly recommend to leverage one of the existing libraries for it for further projects:
https://www.npmjs.com/package/cfenv
Still, please that the parsing of your mongo credentials is properly working (cf e ${app_name}, look for VCAP_SERVICES, manually compare)
If you want to test your service with independent code, here is a sample app i quickly threw together to test all mongodb services bound to it:
package.json:
{
"name": "mongo-tester",
"version": "1.0.0",
"description": "tests all mongodbs via VCAP_SERVICES",
"main": "server.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"author": "Michael Erne",
"license": "MIT",
"dependencies": {
"async": "^2.5.0",
"cfenv": "^1.0.4",
"lodash": "^4.17.4",
"mongodb": "^2.2.31"
}
}
server.js:
var cfenv = require('cfenv'),
_ = require('lodash'),
http = require('http'),
async = require('async'),
MongoClient = require('mongodb').MongoClient
var appEnv = cfenv.getAppEnv();
http.createServer(function (req, res) {
res.writeHead(200, {'Content-Type': 'text/plain'});
res.end('Return something for CF Health Check\n');
}).listen(appEnv.port);
var services = _.values(appEnv.getServices());
var mongodbs = _.filter(services, { label: 'mongodb' });
async.eachLimit(mongodbs, 1, function (m, callback) {
MongoClient.connect(m.credentials.database_uri, function (err, db) {
if (err) {
return callback(err);
}
db.collection("debug").insertOne({"test": true}, function(err, res) {
if (err) return callback(err);
console.log("document inserted successfully into " + m.credentials.database_uri);
db.close();
return callback(null);
});
});
}, function (err) {
if (err) {
console.log(err.stack || err);
console.log('---> mongodb connection failed <---');
return;
}
console.log('---> connection to all BOUND mongodb successful <---');
});
It should print something like the following in its logs if it can connect to any of the bound mongodb services:
document inserted successfully into mongodb://xxx:yyy#zzz.service.consul:1337/databaseName
---> connection to all BOUND mongodb successful <---
If this fails with similar errors, the service instance seems broken (wrong url/port being reported). I would just recreate the service instance in that case and try again.
Finally we have found the problem. The cloud foundry is not allowing to access the MongoDB service during the postinstall phase. So we changed it to prestart and it worked.
Thank you for your help
This error is so common but although I searched a lot of similar questions I did not found a solution to my problem. I installed the module with no problems using "npm install db".
The "server.js" is in the same folder as"node_moludes" and NPM created a "db" folder inside "node_moludes" with all the content.
All NPM commands return success (install, link, list etc), I even added the module to my "package.json" and it also installs with no problem just using "npm install -d".
Despite it all, when I run the server, Nodejs can't find the 'db' module... any help?
nodejs version: 0.10.26
npm version: 1.4.3
server.js
var http = require('http'),
url = require('url'),
db = require('db');
var send = function(response, data){
response.writeHead(200, {
'Content-Type': 'text/plain',
'Access-Control-Allow-Origin': '*'
});
response.end(JSON.stringify({data: data}));
};
http.createServer(function (request, response) {
var query = url.parse(request.url, true).query;
if(query.set) {
db.set(query.set, query.val || '');
send(response, true);
} else if (query.get) {
db.get(query.get, function(data){
send(response, data);
});
} else send(response, query);
}).listen(80);
package.json
{
"name": "xxxxx",
"version": "0.0.1",
"author": "rafaelcastrocouto",
"repository": "git://github.com/rafaelcastrocouto/xxxxx",
"dependencies": {
"db": ">= 1.00.x"
},
"engine": "node >= 0.10.x"
}
It appears the db module was setup without following some Node.js norms. It doesn't contain an index.* file or specify a "main" setting in its package.json to direct Node otherwise.
You should be able to reference the main file within the package directly:
var db = require('db/db');
I am trying to get a setup work with utils, the problem is it can not find the crypto module.
I have install utils and crypto using npm install then when I run my script
node server.js casper.js
I get this error
Error: Cannot find module 'crypto'
phantomjs://bootstrap.js:289
phantomjs://bootstrap.js:254 in require
/var/lib/stickshift/53452520e0b8cd1d870002e1/app-root/data/828422/node_modules/utils/utils.js:7
/var/lib/stickshift/53452520e0b8cd1d870002e1/app-root/data/828422/node_modules/utils/utils.js:117
/var/lib/stickshift/53452520e0b8cd1d870002e1/app-root/data/828422/node_modules/utils/utils.js:118
TypeError: 'undefined' is not a function (evaluating 'utils.inherits(Nightmare, Casper)')
/var/lib/stickshift/53452520e0b8cd1d870002e1/app-root/data/828422/node_modules/nightmarejs/lib/nightmareClient.js:21
/var/lib/stickshift/53452520e0b8cd1d870002e1/app-root/data/828422/node_modules/nightmarejs/lib/nightmareTest.js:16
why can it not find crypto. I have tried all different ways to get this working, but no luck
does any one have any ideas?
package.json file
{
"name": "chat-example",
"version": "0.0.0",
"description": "A chat example to showcase how to use `socket.io` with a static `express` server",
"main": "server.js",
"repository": "",
"author": "Mostafa Eweda <mostafa#c9.io>",
"dependencies": {
"async": "~0.2.8",
"express": "~3.2.4",
"socket.io": "~0.9.14",
"phantomjs": "*",
"casperjs": "*",
"nightmarejs": "*",
"utils": "*",
"casper": "*"
}
}
server.js
var nightmareJS = require('./node_modules/nightmarejs/lib/nightmare').nightmare('test');
nightmareJS.notifyCasperMessage = function(msg) {
if(msg.type == 'statement') {
console.log(msg.msg);
console.log("Nightmare Server says hello.");
}
else if(msg.type == 'dateQuestion') {
console.log(msg.msg);
var d = new Date();
nightmareJS.sendCasperMessage({ time: d.toString(), timeNow: d.getTime()});
}
}
casper.js
casper.start('http://www.google.com', function() {
this.test.assertTitle('Google', 'Google has the correct title');
this.sendMessageToParent({ type: 'statement', msg: 'Hello Nightmare.'})
})
casper.then(function() {
this.waitForMessageResponse({ type: 'dateQuestion', msg: 'What time is it?'}, 'time', function() {
var d = new Date();
this.echo('Nightmare thinks the time is: ' + this.lastDataReceived.time);
this.log('Nightmare thinks the time is: ' + this.lastDataReceived.time, 'debug');
this.test.assert(Math.abs(this.lastDataReceived.timeNow - d.getTime()) < 1000, "Nightmare and Casper's times are within 1000 seconds of each other");
})
});
casper.run(function() {
this.test.done();
});
and then i run the files using
node server.js casper.js
i am trying to get nightmarejs to work but utils cannot find crypto
please someone help i so need this to work