Just installed nodeJS and NPM and nodesupervisor via Terminal in OS 10.5.8.
I have a server running with:
var http = require("http");
function onRequest(request, response) {
console.log("Request received.");
response.writeHead(200, {"Content-Type": "text/plain"});
response.write("Hello World!");
response.end();
}
http.createServer(onRequest).listen(8888);
console.log("Server has started.");
How do I restart the server, without quitting Terminal if the following is updated:
response.write("Hello World, From NodeJS!");
I've seen this "^C" used in Terminal, in a NodeJS video TUT.
Also have node supervisor which appears to handle these changes, but when I attempt to use the watch "-w" command(supervisor -w server.js),
on server.js, nothing ("file being watched" or something) is returned, and the supervisor help screen simply reloads.
NPM: 1.0.96
nodeJS: v0.4.11
Ctrl-C is definitely the way to quit node without quitting terminal all together, just like most command-line apps.
A better option for you might be nodemon. It is specifically for restarting node when changes to files are made.
To install:
npm install nodemon -g
Then simply execute your app with nodemon instead of node.
nodemon server.js
How did you start the node server?
If you are using supervisor then you should be able to do the following:
supervisorctl stop all
Afterwards do whatever you did before to start the thing back up:
supervisord
Related
How do I determine and change both the "DocumentRoot" equivalent (of Apache) and port number on Node.js? I need to test a script file by calling the function and passing some parameters (yes, I know the file can execute it automatically).
There is no "getting started" or mention of this in the documentation.
Apache HTTPD is a generic web server. Node.js is a development framework that includes a standard library for creating HTTP servers. Thus, there isn't a standard configuration for a Node.js based application like there is for Apache HTTPD.
The basic example of writing a web server with Node.js is found at https://nodejs.org/api/synopsis.html#synopsis_example
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}/`);
});
Which is to say, you define where files are loaded from and what port they are served over.
This is where frameworks like Fastify, Hapi, and Express come in. The make it easier to write generic web servers.
I first installed Node.js and it just has a command prompt in Windows. Still not sure the port number.
Node seems to execute scripts from it's directory (e.g. C:\Node.js\). As James mentioned in another answer Node.js doesn't do much on it's own. I followed a tutorial on getting Express to work on Windows. The tutorial failed to mention where scripts are run from so ignore the directions past running the following on the normal command prompt (not Node's console):
Run npm install
npm install express -g
npm install url -g
npm install fresh -g
npm install cookie -g
npm install methods -g
npm install crc -g
npm install send -g
npm install connect -g
npm install commander -g
npm i -D run-func
Okay, the last line of code allows us to run a function and pass parameters which I found via Pawel's answer here.
So now I can execute the following:
node run-func "C:\Users\John\HTTP\index.js" function_name param1 param2
I'm trying a simple sample of node express that I copied from online. The script is below which I think is pretty standard.
var http = require('http');
http.createServer(function(request, response)){
response.writeHead(200);
response.write("hello");
response.end();
}).listen(8080);
console.log('listening on port 8080...');
I used the bash on ubuntu on windows command as follows:
npm init
node SampleServer.js (the name of my file)
When I do this, I expect some response from the command line. But when I enter the "node SamplerServer.js" command, nothing happens. When I direct the browser to port 8080, I get an error message as well.
I'm using nodeclipse and the installing that on my machine was pretty complicated. Prior to any of the steps above, I created an express project in eclipse ide. It seems to perform a lot of pre steps but in the end, I think I'm getting some of the error messages below. I'm mentioning this because I'm thinking perhaps I installed one of the modules wrong.
enter image description here
Start with simple stuff...
Use express-generator to create simple app by the following command
1-> npm install -g express-generator with root or Admin access
2-> Run express demoapp.
3-> Navigate to demoapp
4-> Do npm install
5-> Run from command with npm start: it run by default on http://localhost:3000
Hit that URL from Browser
I'm new to Node.js and wish to run a program using streams. With other programs, I had to start a server simultaneously (mongodb, redis, etc) but I have no idea if I'm supposed to run one with this. Please let me know where I am going wrong and how I can rectify this.
This is the program:
var http = require('http'),
feed = 'http://isaacs.iriscouch.com/registry/_changes?feed=continuous';
function decide(cb) {
setTimeout(function () {
if (Date.now()%2) { return console.log('rejected'); }
cb();
}, 2000);
}
http.get(feed, function (res) {
decide(res.pipe.bind(res, process.stdout));
//using anonymous function instead of bind:
// decide(function () {
// res.pipe(process.stdout)
// });
});
This is the cmd output:
<b>C:\05-Employing Streams\05-Employing Streams\23-Playing with pipes>node npm_stre
am_piper.js
events.js:72
throw er; // Unhandled 'error' event
^
Error: Parse Error
at Socket.socketOnData (http.js:1583:20)
at TCP.onread (net.js:527:27)
</b>
Close nodejs app running in another shell.
Restart the terminal and run the program again.
Another server might be also using the same port that you have used for nodejs. Kill the process that is using nodejs port and run the app.
To find the PID of the application that is using port:8000
$ fuser 8000/tcp
8000/tcp: 16708
Here PID is 16708 Now kill the process using the kill [PID] command
$ kill 16708
I had the same problem. I closed terminal and restarted node. This worked for me.
Well, your script throws an error and you just need to catch it (and/or prevent it from happening). I had the same error, for me it was an already used port (EADDRINUSE).
I always do the following whenever I get such error:
// remove node_modules/
rm -rf node_modules/
// install node_modules/ again
npm install // or, yarn
and then start the project
npm start //or, yarn start
It works fine after re-installing node_modules. But I don't know if it's good practice.
Check your terminal it happen only when you have your application running on another terminal..
The port is already listening..
For what is worth, I got this error doing a clean install of nodejs and npm packages of my current linux-distribution
I've installed meteor using
npm install metor
And got the above referenced error. After wasting some time, I found out I should have used meteor's way to update itself:
meteor update
This command output, among others, the message that meteor was severely outdated (over 2 years) and that it was going to install itself using:
curl https://install.meteor.com/ | sh
Which was probably the command I should have run in the first place.
So the solution might be to upgrade/update whatever nodejs package(js) you're using.
I am starting to learn Node.js and one of the annoying things I am encountering is the starting and stopping of the server when I make a small change to the .js file. Any alternatives?
You can try installing
npm install -g nodemon
And then you run your server
nodemon server.js localhost 8080
That automatically makes you restart the server every time you save new changes
More Info. Nodemon
Use something that watches for file changes and automatically restarts node. nodemon is a good choice.
$ sudo npm install -g nodemon
$ nodemon app.js
server.close
Do not call close before the "listening" event fires.
Either add a callback to listen or add an event manually
server.listen(port, host, function () { server.close(); });
// OR
server.on("listening", function () { server.close(); });
server.listen(port, host);
var net = require('net');
var server = net.createServer(function(socket) {
socket.on('data', console.log);
server.close();
});
server.listen(32323);
var socket = net.createConnection(32323);
// call end to make sure the socket closes
socket.end('hi');
There are nice pre-build modules that can do this for you. Check out nodemon, for example -- install it with npm: npm install -g nodemon
Instead of running node app.js you run nodemon app.js; it will automatically restart your application whenever you make a change.
Learning Node.JS at the moment.
Everything is going fine, just that i have a little challenge with the flow of work.
So i create an HTTP server that listens at a particular port. For example
var http = require("http");
http.createServer(function(request, response) {
response.writeHead(200, {"Content-Type": "text/plain"});
response.write("Hello World");
response.end();
}).listen(8888);
It works fine. Only problem is that when i edit the file that has the above code, and try to start the node process again by typing node server.js i get the following error:
Error: EADDRINUSE, Address already in use.
So i learnt I need to kill the node process using ps before the changes can be reflected and before i can restart.
But this looks like a pain. Do i need to kill the node process anytime i make changes to the server i am writing?
I am sure there is a better way. Any help?
During development I tend to just run node from the command line in a terminal window. When I'm finished with the testing I just Ctrl-C to interrupt the current process which kills node and then press arrow-up enter to restart the process.
my solution is as simple as
npm install dev -g
node-dev app.js
node-dev is the same as 'node' but automatically reruns app.js everytime any file in application dir (or subdir) is changed. it means restarting when static files are changed, too, but should be acceptable for development mode
There isn't any easy way. Authors of node do not like hot-reloading idea, so this is the way it works.
You can hack it if you put your server in a module, require it from the main script, fs.watchFile the .js for changes and then manually stop it as a reaction to a file change, manually deleting it from the module cache (require.cache if I am not mistaken), and require it again.
Or run it in child process and kill and respawn it after a file change (that is, doing automatically what you now do by hand).
You can use something like nodemon (video tutorial about it here) or node-supervisor so that the server auto-restarts when editing files.
If you want to manually do this, then just interrupt the process (CTRL+C) and re-run last command (node server.js).