my nodemon module is not working with node js - node.js

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);

Related

Cloud Foundry MongoDB Error ECONNREFUSED

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

Download Module on NPM start

I want to know if there is a easy way to download file before other code runs. I need file.js to be downloaded first from my server because I am requiring it in my app on different places. I know I can do something like that.
let file = fs.createWriteStream(path.join(__dirname, 'file.js'));
let request = http.get("http://expample.com/file.js",
function(response) {
response.pipe(file);
});
But if I assume correctly, the file is written asynchronously. So when I require that file I have just empty object or error.
So what is the best way to download that file synchronously at first on npm start?
You can get such result using npm script pre hooks.
Assuming your start-up script is called "start" , in your package.json add
script called "prestart" in wich you want to run script that executes file downloading. and in will be automatically run when you call npm run start
For example:
package.json :
{
"name": "test",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"start": "node index.js",
"prestart": "node pre-start.js"
},
"author": "",
"license": "ISC"
}
index.js:
const value = require('./new-file.json');
console.log(value);
pre-start.js:
const fs = require('fs');
setTimeout(function() {
const value = {
"one" : 1,
"two" : 2
};
fs.writeFileSync('new-file.json', JSON.stringify(value));
}, 1000)
Here is a link to article with more detailed information:
http://www.marcusoft.net/2015/08/pre-and-post-hooks-for-npm-scripting.html
The other way is to run your other code after file is written:
let file = fs.createWriteStream(path.join(__dirname, 'file.js'));
let request = http.get("http://expample.com/file.js",
function(response) {
response.pipe(file);
file.on('finish',function(){
// run your code here
}
});

Personality insight input var nodejs

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

TypeError: Cannot read property 'address' of undefined supertest

I need some help to resolve my problem with testing on nodejs codes. I'm using mocha and supertest. I'm confused with the implementation in supertest. I don't know to resolved it. I'm trying to automate downloading a file.
describe('GET /entry/:entryId/file/:id/download', function(){
it('should pass download function', function(done){
this.timeout(15000);
request(app.webServer)
.get('/entry/543CGsdadtrE/file/wDRDasdDASAS/download')
.set('Authorization', 'Bearer eyJ0eXAiOiJKV1QiLCJhbGco')
.expect(200)
.end(function(err, res) {
if (err) return done(err);
console.log(err, res);
done();
});
});
});
I received a similar error from mocha when testing an express app. Full text of error:
0 passing (185ms)
2 failing
1) loading express responds to /:
TypeError: app.address is not a function
at Test.serverAddress (test.js:55:18)
at new Test (test.js:36:12)
at Object.obj.(anonymous function) [as get] (index.js:25:14)
at Context.testSlash (test.js:12:14)
2) loading express 404 everything else:
TypeError: app.address is not a function
at Test.serverAddress (test.js:55:18)
at new Test (test.js:36:12)
at Object.obj.(anonymous function) [as get] (index.js:25:14)
at Context.testPath (test.js:17:14)
I fixed it by adding this to my express server.js, i.e. export the server object
module.exports = app
Typescript users, who are facing this error, check two things:
The express server should have module.exports = app (thanks to #Collin D)
Use import * as app from "./app"
instead of wrong import app from "./app"
I was facing same problem, above solution didn't work for me, some one in my shoes
kindly follow this guy's
exports in server.js should be
module.exports.app = app;
If you have multiple modules than use es6 feature
module.exports = {
app,
something-else,
and-so-on
}
my package.json for version cross ref..
{
"name": "expressjs",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"test": "mocha **/*.test.js",
"start": "node app.js",
"test-watch": "nodemon --exec npm test"
},
"author": "",
"license": "ISC",
"dependencies": {
"express": "^4.16.4",
"hbs": "^4.0.1"
},
"devDependencies": {
"mocha": "^5.2.0",
"supertest": "^3.3.0"
}
}

cloud9 crypto is not working at all been trying for days

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

Resources