Nodemon server won't start - node.js

I was trying to create a simple room based webchat app using socket.io. But I've been facing issues with serving the node server file with node and nodemon. I've tried different ports i.e., 8000, 8080, 80 and I've also tried reinstalling node and nodemon both locally and globally but nothing seems to work. I guess the code is alright because I was following a tutorial (that didn't include any link to the source code though). I'm on windows so I've also used used the command
Set-ExecutionPolicy Unrestricted
Here are the screenshots of Windows power shell and command prompt
PS: I am a newbie, so please consider that I might have missed something basic.
const io = require('socket.io')(8000)
const users = {};
io.on('connection', socket =>{
socket.on('new-user-joined',name =>{
users[socket.id] = name;
socket.broadcast.emit('user-joined', name);
});
socket.on('send', message =>{
socket.broadcast.emit('receive', {message: message,name: user[socket.id]});
});
})

Related

Basic express setup: not sending anything to local port

I created a frontend app and now trying to incorporate backend into it.
ON the same frontend app i added an index.js file in the root directory, and installed express and required it in index.js file.
Very basic setup as below:
const express = require('express')
const cors = require('cors')
const port = process.env.PORT || 3001
const app = express()
app.get('/', (req, res) => {
res.send({
greetings: 'hi'
})
})
app.listen(port, () => {console.log(`Server on port ${port}`)})
Server is successfully on port 3001 as per my terminal, however, on localhost:3001 I'm not seeing any json response I set up in app.get.
It says Cannot GET / instead. When i inspected in devtool(Network) it says 404.
This seems a very straightforward setup, but what could've gone wrong here?
i just figured why. I installed nodemon but my “start” script is “node index.js”. Should’ve used “nodemon index.js”
Working now with nodemon index.ks
Your code is fine, There are no errors, I tested it and it works as expected.
However few things to note, Keep Backend in Seperate folder/dirctory unless required.
Coming back to your question, There are many possiblity such as some modules are not installed properly
try running following command
//this will install if any library is currupt or not installed properly
npm i
if it doesn't work then try clearing cache
Also keep in mind, In nodeJS dev server does not automatically refresh changes, you need to restart server to see changes or you can use dev dependancy called Nodemon (this will auto restart server on saving changes)

Unable to run node API on Ubuntu (AWS)

I have deployed node API on Ubuntu server (AWS) but when I run my app it throw below error given in screen shot. due to I am not able to make API requst.
I have trid to kill port and execute it again but it gives e same error
my node app is running on 8081 on local machine
var connection = mongoose
.connect(url, option)
.then(result => {
app.listen(PORT);
console.log("Running RestHub on port " + PORT)
})
.catch(err => {
console.log(err);
});
after uploading code in Ubuntu sever it does not work
I am struggling to fix this issue since yesterday but could not fix yet.
Please your help would be highly appreciated
Thanks you

hosting a discord bot on cPanel

I have a problem that when I want to turn on my discord bot on my server that uses cPanel, I can't get it to work from the node.js control panel without putting the shell command node index.js into the package.json file and using the run script function of the panel. the problem with this is that the only way to stop the bot is to use the eval command on discord, since I don't have proper terminal access.
In addition to what #Verdigris answered above, you can use Glitch too, just make sure to use Runtime Bot so you can keep your Discord bot up 24/7.
Important: code to add on your main node.js file:
const http = require('http');
const express = require('express');
const app = express();
app.get("/", (request, response) => {
console.log(Date.now() + "Ping Received");
response.sendStatus(200);
});
app.listen(process.env.PORT);
setInterval(() => {
http.get(`http://${process.env.PROJECT_DOMAIN}.glitch.me/`);
}, 280000);
And as always, cheers.
On cPanel you will never have full terminal access, so what I suggest you do is just keep the NPM start script, then create a command for the bot that issues the process.exit() function. This function essentially stops the entire NodeJS Process. If you are looking for an alternative that provides full terminal access I recommend buying a cheap VPS from a decent provider such as OVH.
If your cPanel account has a in-browser terminal, you can enter the virtual environment by pasting the command that appears at the top of the Node.js control panel into there. It is something like:
source ~/nodevenv/<name_of_node_application>/10/bin/activate && cd ~/<path_to_node_application>
You will then have access to node and npm, and can then start your discord bot like you normally would like:
node <name_of_node_application> &
and kill it by running kill -TERM with node's pid, from ps -ax.
However, you can't reliably use the Node.js panel to stop a daemon script, as described here:
cpanel node.js Can't acquire lock for app: app

Automate Functional Testing in node.js

I checked some NPM libraries to test a webpages or web-services. But all of them expect that the server is already running. Since I want to automate functional testing, how can I setup NPM package in such a way that
It can start the server
Test the application
Stop the server
So that I can test it locally, as well as on online CI tools like travis-ci or circleci.
Case 1: Webservice
I wrote a NPM package which starts nodejs HTTP(s) server. It can be started from command line $stubmatic. Currently, I use 2 approaches to test it,
manual : I manually start it from command line. Then run the tests.
Automatic: I use exec module to run a unix command which can start the application and run pkill command to kill the application. But for this automation, my application need to be installed on testing machine.
Case 2: Website
I have create a NPM package: fast-xml-parser and created a demo page within the repo so that I can be tested in the browser. To test the demo page, I currently start a local server using http-server npm package manually. Test the application.
What can be the better way to write automate functional tests for node js applications?
Note:
I never used task runners like gulp or grunt. So I'm not sure if they can help in this case.
In case 1, my application starts node js native HTTP server. I'm not using any 3rd party application like express currently.
This question mentions a new Docker container system for Travis that could be duplicated locally. It might be a way: How to run travis-ci locally
Did you look at supertest (SuperAgent driven library for testing HTTP servers) and expect (Assertions library)(documented here) with mocha (Test Framework)?
I use them and I never had any kind of problems for all the tests I do until now.
The documention in the links contains all the informations you need to build up your test.
Case 1: Webservice
Problem 1
As nodejs server.close() was not working. I copied paste this snippet in every test file which is starting my webservice.
try{
server.setup(options);
server.start();
}catch(err){
console.log(err);
}
Once all the tests are completed, server stops.
**Problem 2
I was using chai-http incorrectly. Here is the complete working solution.
//Need to be placed before importing chai and chai-http
if (!global.Promise) {
global.Promise = require('q');
}
var server = require('.././lib/server');
var chai = require('chai')
, chaiHttp = require('chai-http');
chai.use(chaiHttp);
try{
server.setup(someoptions);
server.start();
}catch(err){
console.log(err);
}
describe('FT', function () {
describe('scenario::', function () {
it('responds to POST', function (done) {
chai.request("http://localhost:9999")
.post('/someurl')
.then(res => {
expect(res.status).toBe(200);
//console.log(res.text);
done();
}).catch( err => {
console.log(err);
done();
});
});
});
Case 2: Website This was quite simple.
I used http-server to start the server so my html files can be accessed.
I used zombie js for browser testing. (There are many other options available for browser testing)
Here is the code
process.env.NODE_ENV = 'test';
const Browser = require('zombie');
const httpServer = require('http-server');
describe("DemoApp", function() {
var browser = new Browser({site: 'http://localhost:8080'});
var server = httpServer.createServer();
server.listen(8080);
beforeEach(function(done){
browser.visit('/', done);
});
describe("Parse XML", function() {
it("should parse xml to json", function(done) {
browser.pressButton('#submit');
browser.assert.text('#result', 'some result text');
done();
});
});
afterEach(function(){
server.close();
})
});

http server listening in old port

First i installed the node js with webmatrix and ran a sample node js app. the app was assigned a random port. http://localhost:62369/. After that i installed the express module. As said in their doc. i wrote,
var app = express();
app.get('/',function (req, res) {
res.send('hello world!!');
})
app.listen(3000);
Then i restarted the server. The launched browser was still pointing to http://localhost:62369/ instead of port 3000. Moreover http://localhost:3000/ was not working.
I suggest you to run this code so you can see if you have any problem on saving the code with your IDE:
var app = express(),
port = 4555;
app.get('/',function (req, res) {
res.send('hello world!!');
})
console.log("Server is running on " + port);
app.listen(port);
After that, you need to change the port variable only. It's helpful if you comment what you see after running this code on the console.
make sure that you've saved your code in your file (open it with another editor, maybe something's wrong with your editor), close the command line window and open it again. try to run server. I'm sure the problem is not because of node or express. Try to check everything again.
And also run your server with command line:
cd path/folder
node myFile
I don't know what are you using to run server, but if it's something with UI (in comments you mentioned a click) it can cache your code or something like that. So it's safer to run with commend line.

Resources