Start and stop gulp-webserver - javascript

I am trying to start and stop gulp-webserver in different gulp tasks like below:
gulp.task('webserver', ['build'], function () {
gulp.src([config.build, config.base])
.pipe(webserver({
livereload: false,
directoryListing: false,
open: true
}));
});
gulp.task('webserver-stop', function () {
var stream = gulp.src([config.build, config.base])
.pipe(webserver());
stream.emit('kill');
});
I am able to successfully start the server but when I try to stop the using gulp webserver-stop, it gives following error.
[19:36:30] Finished 'webserver-stop' after 27 ms
events.js:160
throw er; // Unhandled 'error' event
^
Error: listen EADDRINUSE 127.0.0.1:8000
at Object.exports._errnoException (util.js:1008:11)
at exports._exceptionWithHostPort (util.js:1031:20)
at Server._listen2 (net.js:1253:14)
at listen (net.js:1289:10)
at net.js:1399:9
at GetAddrInfoReqWrap.asyncCallback [as callback] (dns.js:65:16)
at GetAddrInfoReqWrap.onlookup [as oncomplete] (dns.js:84:10)
I have no significant experience with gulp and javascript before,
Any help to fix this please.

When you run gulp webserver and then gulp webserver-stop you have two processes. Those two processes know nothing of each other.
So when you invoke webserver() in webserver-stop that just starts another webserver instance. It doesn't connect to the already running instance or anything like that. And since there is already one webserver running on port 8000 you get an EADDRINUSE error.
Instead your webserver-stop task needs to send a message to the running webserver that causes it to shut down.
Since you're already running a webserver you might as well send that message over HTTP. You can use the middleware option of gulp-webserver to achieve this:
var gulp = require('gulp');
var webserver = require('gulp-webserver');
var http = require('http');
gulp.task('webserver', function () {
var stream = gulp.src(['.'])
.pipe(webserver({
livereload: false,
directoryListing: false,
open: true,
middleware: function(req, res, next) {
if (/_kill_\/?/.test(req.url)) {
res.end();
stream.emit('kill');
}
next();
}
}));
});
gulp.task('webserver-stop', function (cb) {
http.request('http://localhost:8000/_kill_').on('close', cb).end();
});
Now you can invoke gulp webserver-stop in another terminal window or simply open http://localhost:8000/_kill_ in a browser to shut down the running webserver instance.

Related

Hapi Server Crashes upon Request

I am making trying to take a backend using Hapi for the first time but every time a request is sent to the server it crashes. Sometimes I do get a response but the server eventually crashes on its own.
The error I get is:
TypeError: Cannot read properties of null (reading 'statusCode')
at Request._finalize (C:\Users\prakh\Desktop\Angular\buy-and-sell-backend\node_modules\#hapi\hapi\lib\request.js:491:31)
at Request._reply (C:\Users\prakh\Desktop\Angular\buy-and-sell-backend\node_modules\#hapi\hapi\lib\request.js:428:18)
at Request._execute (C:\Users\prakh\Desktop\Angular\buy-and-sell-backend\node_modules\#hapi\hapi\lib\request.js:274:14)
at processTicksAndRejections (node:internal/process/task_queues:96:5)
The code is simple since I am only testing right now:
import Hapi from '#hapi/hapi'
const start = async () => {
const server = Hapi.server({
port: 8000,
host: 'localhost',
});
server.route({
method: 'GET',
path: '/hello',
handler: (req, h) => {
return 'Hello!';
}
});
await server.start();
console.log(`Server is listening on ${server.info.uri}`)
}
process.on('unhandledRejection', err => {
console.log(err);
process.exit(1);
});
start();
I am using Node v16.17.0 and the command I use to run it is npx babel-node src/server.js
I am not sure what I am doing wrong here.
Found the fix.
Had to update the Hapi version that I was using.
Use: npm uninstall #hapi/hapi
and then: npm install #hapi/hapi
Hapi 20.2.2 works

NodeJS , gulp , Error: listen EADDRINUSE :::3000

i am working with NodeJS and i am using gulp.
My foler look like that :
Root
dist
node_modules
src
index.html
gulpfile.js
package.json
My gulpfile is :
"use strict";
var gulp = require('gulp');
var connect = require('gulp-connect'); // runs a local dev server
var open = require('gulp-open'); // open a URL in a web browser
var config ={
port : 3000,
devBaseUrl : 'http://localhost',
paths:{
html:'./src/*.html',
dist:'./dist'
}
}
//Start a local development server
gulp.task = ('connect' , function(){
connect.server({
root:['dist'],
port: config.port,
base: config.devBaseUrl,
});
});
gulp.task('open', ['connect'], function(){
gulp.src('dist/index.html').pipe(open({uri: config.devBaseUrl + ":" + config.port + '/'}))
});
gulp.task('html',function(){
gulp.src(config.paths.html)
.pipe(gulp.dest(config.paths.dist))
.pipe(connect.reload());
});
gulp.task('default', ['html', 'open']);
When i am type 'gulp' in the cmd i get this error :
C:\Users\maor\Documents\NodeProject\2>gulp
[13:18:28] Using gulpfile ~\Documents\NodeProject\2\gulpfile.js
[13:18:28] Server started http://localhost:3000
events.js:160
throw er; // Unhandled 'error' event
^
Error: listen EADDRINUSE :::3000
at Object.exports._errnoException (util.js:1018:11)
at exports._exceptionWithHostPort (util.js:1041:20)
at Server._listen2 (net.js:1262:14)
at listen (net.js:1298:10)
at Server.listen (net.js:1394:5)
at ConnectApp.server (C:\Users\maor\Documents\NodeProject\2\node_modules\gulp-connect\index.js:57:19)
at new ConnectApp (C:\Users\maor\Documents\NodeProject\2\node_modules\gulp-connect\index.js:37:10)
at Object.server (C:\Users\maor\Documents\NodeProject\2\node_modules\gulp-connect\index.js:170:12)
at Gulp.gulp.task (C:\Users\maor\Documents\NodeProject\2\gulpfile.js:18:10)
at Object.<anonymous> (C:\Users\maor\Documents\NodeProject\2\gulpfile.js:29:6)
I really dont know what the problem is , i already checked and the port : 3000 is free. can you guys help me figure what the problem is ?
Are you running any other applications that might be using port 3000?
It's possible that a previous instance of node may still be running, even if you intended to kill it. Check your processes, I sometimes get this issue and generally use
killall node
to resolve it.
This problem arise, when node process already running on the port.
You can fix it by
pkill node
OR you can use this
killall node
you still see node process with this command: ps aux | grep node.
If you are using windows, then open task manager & in process tab, search node & right click on that process & end process.
Surely it will work.
Or better still you can change the port number to something else like 8000.

How to stop node-server based interval script?

I am creating an application in Nodejs using Expressjs framework.
I was try to execute some script after every minute using setInterval() JavaScript method.
When I start my server by node app.js the script run successfully. But when I stop the server by Ctrl+c and trying to restart it then it says that the 3000 (my server port) already in use.
I cannot restart my server neither access my website. I am using Ubuntu.
I have used all the following commands but it doesn't stop.
fuser -k 3000/tcp
kill processNumber
killall node
Code:
router.get("/trackplayers", function(req, res, next ) {
// Run in every minute
setInterval(function(){
console.log('Players tracking is under process..');
}, 60000);
});
Thanks in advance!
Be sure to exit the process cleanly. The following code will gracefully terminate an express application.
var express = require("express");
var app = express();
var server = app.listen(3000);
// Respond to 'Ctrl+C'
process.on("SIGINT", function () {
// stop accepting connections
server.close(function () {
// connections are closed
// exit the process
process.exit(0);
});
});
// Server is shutting down
process.on("SIGTERM", function () {
// stop accepting connections
server.close(function () {
// connections are closed
// exit the process
process.exit(0);
});
});

NodeJS Error EADDRINUSE and HTML file not rendering, instead shows html codes

I'm new kid on the block with NodeJS. Right now im following a basic tutorial of NodeJS, so far so good.
But I have a problem using fs.createReadStream method:.
var http = require("http");
var fs = require("fs");
function fourOHfour(response) {
response.writeHead(404, {"Content-Type": "text/plain"});
response.write("four oh four.....");
response.end();
}
function onRequest (request, response) {
if(request.method == 'GET' && request.url == '/'){
response.writeHead(200, {"Content-Type": "text/plain"});
fs.createReadStream("./index.html").pipe(response);
}
else{
fourOHfour(response);
}
}
http.createServer(onRequest).listen(8888);
console.log("server is running......");
When I go on my browser and type localhost:8888, it should be rendering the index.html file in HTML but the result is wrong, all I get is a bunch of codes of index.html file - plain text.
Meanwhile in my sublime compiler, I've got no error in regards to this case. Until i try to edit my code, whatever I cahnge, it will give me an error like this:
If that thing happen, I cant fix the error unless I restart the laptop, then everything running well again. At least my compiler say that the server is running... Even thought my localhost:8888 still not rendering the HTML file.
You are specifying your content type as: text/plain which means the page will not render in HTML but instead, plain text. This is why you see the "codes" from your HTML file instead of the actual HTML being rendered.
To fix that problem, set the content type to text/html like so:
response.writeHeader(200, {"Content-Type": "text/html"});
In regards to the error you posted, "EADDRINUSE"
EADDRINUSE means that the port number which listen() tries to bind the server to is already in use.
So, in your case, there must be running a server on port 8888 already.
Check for the listening event like this, to see if the server is really listening:
var http=require('http');
var server=http.createServer(function(req,res){
res.end('test');
});
server.on('listening',function(){
console.log('ok, server is running');
});
server.listen(8888);
EADDRINUSE - seems like port is busy by another process or maybe by same nodejs process that don't want to close.
try to kill process:
killall node
about code - try this:
var http = require("http"),
fs = require("fs"),
URL = require('url');
function output(response, body, status) {
status = status || 200;
response.writeHead(status, {"Content-Type": "text/html"});
response.end(body);
}
function fourOHfour(response) {
output(response, 404, "four oh four...");
}
function onRequest (request, response) {
var uri = URL.parse(request.url).pathname; // extractin URI part
var method = request.method || 'GET'; // detecting method otherwise GET
if(method == 'GET' && uri == '/'){
// reading file
fs.readFile(__dirname+'/index.html', function(err, data) {
if(err) { // if error happen, output error
output(response, err, 500);
return;
}
output(response, data); // ouput html body
});
return;
}
fourOHfour(response);
}
var httpServer = http.createServer();
httpServer.on('request', onRequest);
httpServer.listen(8888);
To run Your code in production do following in terminal:
install forever:
sudo npm install -g forever # remove sudo word if You use windows, or You're already root user
start app using forever:
forever start app.js
To run Your code in development environment:
install nodemon:
sudo npm install -g nodemon # remove sudo word if You use windows, or You're already root user
run Your app using nodemon:
nodemon app.js
Forever will keep Your app running and will output logs which You can see using:
forever list # lists running processes
forever logs # shows logs that outputs forever
forever logs 0 # read logs of 0-th process
To restart forever process:
forever restartall # restarts all forever instances
forever restart 0 # restarts first process
To stop:
forever stopall
forever stop 0
About Nodemon: it's a tool that watches changes in Your file and restarts it automatically, no need to stop-start Your app, so that's why I prefer nodemon in dev environment

gulp-livereload with vagrant environment : livereload.js not accessible

I have a problem using gulp-livereload in my vagrant environment (generated with puphpet).
My computer is a Windows Host, and the VM a Debian.
I use this gulpfile :
var gulp = require('gulp'),
less = require('gulp-less')
lr = require('tiny-lr'),
livereload = require('gulp-livereload'),
server = lr()
;
gulp.task('less', function () {
gulp.src('assets/less/*.less')
.pipe(less())
.pipe(gulp.dest('build/css'))
.pipe(livereload(server))
;
});
gulp.task('watch', function() {
gulp.watch('assets/less/*.less', ['less']);
livereload.listen(35729, function(err){
if(err) return console.log(err);
});
});
gulp.task('default', ['watch', 'less']);
And when Chrome Extension add the magic JS file I obtain this message :
Failed to load resource: net::ERR_CONNECTION_TIMED_OUT http://markup.dev:35729/livereload.js?ext=Chrome&extver=0.0.5
But in my VM, if I run the following command line, I get it
wget http://localhost:35729/livereload.js?ext=Chrome&extver=0.0.5
I don't have enough information to be certain, but I would guess that your problem is you are trying to access the page from the host, but the livereload port isn't forwarded (the VM has it's own IP address and vagrant can be configured to forward certain ports to the host so that they "appear" to be local on the host).
Try adding the following line to your Vagrantfile:
config.vm.network "forwarded_port", guest: 35729, host: 35729
(For documentation see: https://docs.vagrantup.com/v2/networking/forwarded_ports.html)
Alternatively if you are directly hitting the VM (that is you have markup.dev mapped to the guest's IP) it may be worth verifying that there is not a firewall configured on your VM which might block the livereload port from external access.
In my case, the port forwarding worked automagically. However, I had to specify the VM's IP as host:
livereload.listen({
host: '192.168.33.10'
});
Update: Passing null works, too:
livereload.listen({
host: null
});
I guess that the underlying http server behaves differently when passing 'localhost' explicitly.

Categories

Resources