NodeJS autorefresh server - node.js

Ok, I'm using NetBeans and I have this piece of code:
var express = require("express");
var app = express();
app.get("/", function (req, res) {
res.send("Hi");
});
app.listen(8000);
When I click run file it starts listening on the port 8000. But, when I make a change and then run file again it cannot start listening on port 8000, because the previous one was not terminated. I have the option checked "Apply Code Changed on Save" in Options->HTML/JS->Node.js. How to refresh previously started server instead of starting the new one one?

Ok, the project in NetBeans was set to be run as WebApplication, but not as NodeJS Application and thus it didn't start the nodeJS server. In order to change it you have to right click on your project and go to "Properties"->"Run" and then change "Run As:" to "Node.js Application" and check "Restart running Node.js process".

The 'Apply Code Changed on Save' is imho for debugging. You can run the project instead of file, if you run project and it has been already running, then NetBeans will stop the running project (e.g to free the port) and it will continue and run the projec

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)

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

Do not know how to start debugging a Node.js code in JetBrains WebStorm

I am trying to learn to debug a Node.js code in WebStorm. The code is the simple "Getting Started" code from here:
const http = require('http');
const hostname = '127.0.0.1';
const port = 3000;
const server = http.createServer((req, res) => {
res.statusCode = 200;
res.setHeader('Content-Type', 'text/plain');
res.end('Hello World\n');
});
server.listen(port, hostname, () => {
console.log(`Server running at http://${hostname}:${port}/`);
});
The above code works correctly after I ran node app.js at command line and visited http://localhost:3000. Next I tried to debug it locally in JetBrains WebStorm following instructions here. This is the debug configuration of Node.js application in WebStorm:
I clicked the bug icon to run the Node.js code under debugging mode. This is the output:
"C:\Program Files (x86)\JetBrains\WebStorm 10.0.3\bin\runnerw.exe" "C:\Program Files\nodejs\node.exe" --debug-brk=24163 --nolazy --inspect app.js
Debugger listening on ws://127.0.0.1:24163/bffa51bd-74bd-4257-8174-2c8ab3768e17
For help see https://nodejs.org/en/docs/inspector
I guess that it is equivalent to running the "node app.js" command. The instruction says I need to "Perform the steps that will trigger the execution of the code with the breakpoints." I guess that means I open the URL "http://localhost:3000" in browser to send a request to the web server that the app.js is implementing, and I did it. I have set up breakpoints on every line of the source app.js and I expected that the breakpoints should be hit somewhere in the source, but the browser reported an "Unable to connect" error and nothing happened in WebStorm -- no breakpoint is hit. I have checked the instructions but could not figure out what I am missing. Could you please help me with this problem? If you need more information please let me know. Thanks a lot!
PS: app.js is in the ...\test folder.
==Edit:==
PS2: The browser can print "Hello world" just because "node app.js" is still running. After I terminated it, the browser reports "Unable to connect". So that means the URL does not know how to connect to the webserver launched by WebStorm debugger. Is the port wrong?
PS3: This is what returns from http://localhost:31496/json/list (the port number changes in every debugging session). Hope it can help troubleshooting.
description "node.js instance"
devtoolsFrontendUrl "chrome-devtools://devtools/bundled/inspector.html?experiments=true&v8only=true&ws=127.0.0.1:31496/0f03cac0-648f-4c13-9cb9-39bb5e3a81a6"
faviconUrl "https://nodejs.org/static/favicon.ico"
id "0f03cac0-648f-4c13-9cb9-39bb5e3a81a6"
title "app.js"
type "node"
url "file://E:..._test_app.js"
webSocketDebuggerUrl "ws://127.0.0.1:31496/0f03cac0-648f-4c13-9cb9-39bb5e3a81a6"
As far as I can see, you are using webStorm 10. It's quite old and doesn't support new debugger protocol introduced in recent Node.js updates.
Please downgrade Node.js to v. 4.x (at least) or, better, upgrade Webstorm to 2017.3

application.js wont start but debug works

I am new to node.js and I want to get webserver running but I got this problem where trying to debug application by running node ./bin/www works perfectly but trying to launch it by node app.js dosen't do anything.
When i type out node app.js in terminal blank line appears like its loading something and dissapears in few seccods without any error or starting application.
The problem is that app.js is exporting an app object, not starting a server. If you look at the code for bin/www you'll see that it loads the app object and uses it to start a server.
#!/usr/bin/env node
var debug = require('debug')('tmp');
var app = require('../app');
app.set('port', process.env.PORT || 3000);
var server = app.listen(app.get('port'), function() {
debug('Express server listening on port ' + server.address().port);
});
You need to either start the app using bin/www, or modify and move that code to the end of app.js if you don't want the separate start script.
If you want to see the debug messages, you need to add the DEBUG environment variable to your shell session. For development environments, you could do this automatically by placing it in your .bashrc file.
export DEBUG=express:*
Or if you do not want to do that, you can just do this:
DEBUG=express:* node ./bin/www
http://expressjs.com/guide.html#debugging-express

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