Restart express server every time a request is made to an endpoint - javascript

basically I would like to 'restart' it every time a client sends a request to /reset, how can I do that? any help is extremely valuable, I don't know how to approach this yet

As #jfriend00 mentioned, You can use pm2 like applications to monitor the process. Below is simple steps that can be followed.
Node Js code: Exit the process on route
const express = require("express");
const app = express();
app.get("/", (_, res) => res.send("hello"));
app.get("/restart", (_, res) => {
process.exit(0);
});
app.listen(8080, () => console.log("Server is running on :8080"))
Run server using pm2 in watch mode:
./node_modules/.bin/pm2 start app.js --watch
He also mentioned that you should not use this in the production environment. I support that statement. You should not use this approach in prod environment.

Related

node index.js command start and end server in the same time

I did install WSL2 and ubuntu 22.04 distribution on windows 11. I configured envoirment, installed nvm, node v.16.17.1, next in my folder did npm init, installed express, created index.js file within simple structure:
const express = require('express')
const app = express()
const port = 3000
app.get('/', (req, res) => {
res.send('Hello World!')
})
app.listen(port, () => {
console.log(`Example app listening on port ${port}`)
})
When i tap node index.js nothing happen.
image
In my second computer with ubuntu 20.04 distribution everything work fine. Does anyone know what to do?
How about doing debugging by referring to https://expressjs.com/en/guide/debugging.html?
like this,
DEBUG=express:* node index.js
If no other problem is found, it would be good to use the --inspect options.
https://nodejs.org/en/docs/guides/debugging-geting-started/
Problem resolve. File need to be SAVE before calling from terminal....

Can't run puppeteer in react app, Module not found: Can't resolve 'ws' when compiling

I was wondering if it was possible to run puppeteer in my react app. Whenever I try to run puppeteer in my react app I get "Module not found: Can't resolve 'ws'". I've tried installing ws but will still get the same error.
Simple answer : You can't run puppeteer in react app.
React is a client side framework. which means it runs in browser.
While puppeteer is a NodeJS lib, it needs Node.js and runs on server side.
Puppeteer is a Node library which provides a high-level API to control Chrome or Chromium over the DevTools Protocol. Puppeteer runs headless by default, but can be configured to run full (non-headless) Chrome or Chromium.
Expanding on the above answer. You cannot directly run Puppeteer on a react app. React app is a frontend framework and you would need Puppeteer to run on a node js, server. It's a simple "fix" and I wanted to explain it a little more than the answer above does.
The steps to get them to work together would be.
Setup an express server. You can create an express server like so:
Separate directory reactServer. Npm init directory and npm i express.
In your express server you allocate a path
const express = require('express')
const app = express()
const port = 5000
app.get('/', (req, res) => {
res.send('Hello World!')
})
app.get('/my-react-path', (req, res) => {
// run any scripts you need here
})
app.listen(port, () => {
console.log(`Example app listening at http://localhost:${port}`)
})
Then your react app will interact with your server like so:
localhost:5000/my-react-path
In the my-react-path you can create a function that fires up puppeteer and does all the things you want on the server side and it can return whatever results to React. The above example is just to get you started it doesn't have anything related to puppeteer.

Express performance requiring modules

Having a question regarding the performance of a NodeJS application.
When I have the following express app in NodeJS:
const app = require('express')();
const about = require('./about');
app.use('/about', about);
app.listen(3000, () => console.log('Example app listening on port 3000!'));
My current understanding is that only when the server is started up it does need to require() these files using commonJS modules.
Question:
Does the express application has to execute the require() statements with every request to the server or is this only necessary when starting the server?
Any extra information about how express works under the hood would be nice.
No, those require are only run once when you start the app. It would be different if you include those in the router functions.
app.use('/about', (req, res) => {
const some = require('some');
});
Still in this scenario, modules require are cached so it's not such a big deal.

Make node.js server listen on Heroku

I'm building a simple app that connects to a Node.js server.
Now, I've successfully tested the server locally: I run "node server.js" on a cmd window, the server's listening, and then I can use whichever routes I'd like.
However, using "http://localhost:8080/" obviously isn't going to work on my phone, and therefore I've deployed my code to Heroku. I can run this file there, and get the reply it sends, but my question is - how do I make it continuously listen?
I tried searching for an answer online, but no luck..
here's my server.js file:
// dependencies
var express = require('express');
var app = express();
var port = Number(process.env.PORT || 8080);
var routes = require('./routes/api');
var bodyParser = require('body-parser');
//express
app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());
//routes
app.use('/api', routes);
app.get('/', function(req, res) {
res.send('Our first route is working! :)');
});
app.get('/test', function(req, res) {
res.send('Testing successful!! :)');
});
//start the server
app.listen(port, function() {
console.log('Listening on port ' + port);
});
Not sure what do you mean by "continuously listen". Heroku builds the project and runs when you deploy it. All you need to do is create a heroku project and push your code to instance. Monitor the logs on heroku so that you know that your project is successfully deployed and there is no error. You will have to install heroku toolbelt to execute heroku related commands. All the details for the deploying node application to heroku are provided here
To send your server to heroku, follow the steps provided in this link https://devcenter.heroku.com/articles/git
Hope that helps
The call to
app.listen(port, ...
does continuously listen.
Assuming your deploy worked, go to your Heroku app's url ( e.g. http://cookienator.herokuapp.com/api/test) and notice it's listening.
app.listen(process.env.PORT,process.env.IP);
This may work.
It didnt work on running port argument for me.
The above code worked for me.
Also dont forget to add app.js or start page in package.json

node.js /socket.io/socket.io.js not found

i keep on getting the error
/socket.io/socket.io.js 404 (Not Found)
Uncaught ReferenceError: io is not defined
my code is
var express = require('express'), http = require('http');
var app = express();
var server = http.createServer(app);
var io = require('socket.io').listen(server);
server.listen(3000);
and
<script src="/socket.io/socket.io.js"></script>
what is the problem ???
any help is welcome!
Copying socket.io.js to a public folder (something as resources/js/socket.io.js) is not the proper way to do it.
If Socket.io server listens properly to your HTTP server, it will automatically serve the client file to via http://localhost:<port>/socket.io/socket.io.js, you don't need to find it or copy in a publicly accessible folder as resources/js/socket.io.js & serve it manually.
Code sample Express 3.x -
Express 3 requires that you instantiate a http.Server to attach socket.io to first
var express = require('express')
, http = require('http');
//make sure you keep this order
var app = express();
var server = http.createServer(app);
var io = require('socket.io').listen(server);
//...
server.listen(8000);
Happy Coding :)
How to find socket.io.js for client side
install socket.io
npm install socket.io
find socket.io client
find ./ | grep client | grep socket.io.js
result:
./node_modules/socket.io/node_modules/socket.io-client/dist/socket.io.js
copy socket.io.js to your resources:
cp ./node_modules/socket.io/node_modules/socket.io-client/dist/socket.io.js /home/proyects/example/resources/js/
in your html:
<script type="text/javascript" src="resources/js/socket.io.js"></script>
It seems that this question may have never been answered (although it may be too late for the OP, I'll answer it for anyone who comes across it in the future and needs to solve the problem).
Instead of doing npm install socket.io you have to do npm install socket.io --save so the socket.io module gets installed in your web development folder (run this command at the base location/where your index.html or index.php is). This installs socket.io to the area in which the command is run, not globally, and, in addition, it automatically corrects/updates your package.json file so node.js knows that it is there.
Then change your source path from '/socket.io/socket.io.js' to 'http://' + location.hostname + ':3000/socket.io/socket.io.js'.
... "You might be wondering where the /socket.io/socket.io.js file
comes from, since we neither add it and nor does it exist on the filesystem. This is
part of the magic done by io.listen on the server. It creates a handler on the server
to serve the socket.io.js script file."
from the book Socket.IO Real-time Web
Application Development, page 56
You must just follow https://socket.io/get-started/chat/ and all will work.
var app = require('express')();
var http = require('http').Server(app);
var io = require('socket.io')(http);
http.listen(3000, function(){
console.log('listening on *:3000');
});
If you are following the socket.io tutorial https://socket.io/get-started/chat/, you should add this line as below.
app.use(express.static(path.join(__dirname, '/')))
This is because in the tutorial, Express will only catch the url
/ and send the file of index.html.
app.get('/', function (req, res) {
res.sendFile(__dirname + '/index.html')
})
However, in the index.html, you have a script tag (<script src="/socket.io/socket.io.js"></script>) requests the resouce of socket.io-client, which is not routed in index.js (it can be found in console-network that the url is http://localhost:3000/socket.io/socket.io.js).
Please check the directory path mentioned in your code.By default it is res.sendFile(__dirname + '/index.html');
make sure you index.html in proper directory
Steps to debug
npm install socket.io --save in static files (index.html) for example, you may have installed it globally and when you look at the debugger, the file path is empty.
Change your script file and instantiate the socket explicitly adding your localhost that you have set up in your server file
<script src="http://localhost:5000/socket.io/socket.io.js"></script>
<script>
const socket = io.connect("localhost:5000");
$(() =>
Double check that the data is flowing by opening a new browser tab and pasting http://localhost:5000/socket.io/socket.io.js you should see the socket.io.js data
Double check that your server has been set-up correctly and if you get a CORs error npm install cors then add it to the server.js (or index.js whatever you have chosen to name your server file)
const cors = require("cors");
const http = require("http").Server(app);
const io = require("socket.io")(http);
Then use the Express middleware app.use() method to instantiate cors. Place the middleware this above your connection to your static root file
app.use(cors());
app.use(express.static(__dirname));
As a final check make sure your server is connected with the http.listen() method where you are assigning your port, the first arg is your port number, for example I have used 5000 here.
const server = http.listen(5000, () => {
console.log("your-app listening on port", server.address().port);
});
As your io.on() method is working, and your sockets data is connected client-side, add your io.emit() method with the callback logic you need and in the front-end JavaScript files use the socket.on() method again with the call back logic you require. Check that the data is flowing.
I have also edited a comment above as it was the most useful to me - but I had some additional steps to take to make the client-server connection work.
If you want to manually download "socket.io/socket.io.js" file and attaché to html (and not want to get from server runtime) you can use https://cdnjs.com/libraries/socket.io
like
<script src="https://cdnjs.cloudflare.com/ajax/libs/socket.io/4.0.1/socket.io.min.js" integrity="sha512-eVL5Lb9al9FzgR63gDs1MxcDS2wFu3loYAgjIH0+Hg38tCS8Ag62dwKyH+wzDb+QauDpEZjXbMn11blw8cbTJQ==" crossorigin="anonymous"></script>
while this doesn't have anything to do with the OP, if you're running across this issue while maintaining someone else's code, you might find that the problem is caused by the coder setting io.set('resource', '/api/socket.io'); in the application script, in which case your HTML code would be <script>type="text/javascript" src="/api/socket.io/socket.io.js"></script>.
If this comes during development. Then one of the reasons could be you are running a client-side file(index.html). But what you should do is run your server(example at localhost:3000) and let the server handle that static file(index.html). In this way, the socket.io package will automatically make
<script src="/socket.io/socket.io.js"></script> available on the client side.
Illustration(FileName: index.js):
const path = require('path');
const express = require('express');
const socketio = require('socket.io');
const port = 3001 || process.env.PORT;
const app = express();
const server = http.createServer(app);
const io = socketio(server);
//MiddleWares
app.use(express.json());
app.use(
express.urlencoded({
extended: false,
})
);
app.use(express.static(__dirname + '/public'));
app.get('/', (req, res) => {
res.sendFile('index.html');
});
io.on('connect', (socket) => {
console.log('New user joined');
}
server.listen(port, () => {
console.log(`App has been started at port ${port}`);
});
After this run your server file by the command
node index.js
Then open the localhost:${port}, Replace port with given in the index.js file and run it.
It solved my problem. Hope it solves yours too.

Categories