Configure nodemon to refresh same tab - node.js

This could be really rookie. I want to know if there is a way that I can configure nodemon to refresh the same tab instead of opening a new tab each time I make a change in my js files.

nodemon is not able to do that. What you are looking for is something like browser-sync or LiveReload.js.

I use a package called reload. Assuming you are doing this on your FE and that you already installed express.js and nodemon
first install reload
npm install --save-dev reload
Than create a index.js file or server.js or whatever name your want
this is my index.js:
const express = require('express')
const http = require('http')
const reload = require('reload')
const opn = require('opn')
const app = express()
app.engine('html', require('ejs').renderFile)
app.set('view engine', 'html')
app.set('src', './src')
app.use(express.static('src'))
app.get('/', (req, res) => res.render('index'))
const server = http.createServer(app)
server.listen(8080, function() {
console.log('Listening to port 8080...')
})
opn('http://localhost:8080')
reload(app)
the opn package can be intalled with
npm install opn
it will automatically open your localhost once you type npm start on your terminal
on HTML you have to insert something like this after the closing body tag:
</body>
<script src="/reload/reload.js"></script>
and on package.json the following:
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1",
"start": "nodemon index.js -e els,js,html,css,json"
},
The only problem with this is that it will reopen the browser every time you make a change to those files and well as reload the current opened one sure to the opn package. I am still going to create a function to prevent that, eventually. Hope that helps!

Its Simple.
To run your server use
npm start
instead of
nodemon server

Just run npm start nodemon server.
It works for me. Make sure you have latest nodemon version installed.

Related

Node.JS doesn't refresh the Nunjuck template

I'm using Node.JS and Nunjuck to make my templates.
When I change something on my .njk files, I have to stop the Node.JS server and start it back again so that the changes reflect on my browser (localhost:80).
Here is how my app.js (server) looks like:
var app = require("express")(),
nunjucks = require('nunjucks'),
server = require("http").createServer(app),
io = require("socket.io").listen(server)
path = require("path");
nunjucks.configure('views',
{
autoescape: true,
express: app
});
app.get("/", function (req, res)
{
res.render(__dirname + "/views/index.njk");
});
server.listen(80);
And in my index.njk, I have two lines:
{% set x = 5 %} and {{ x }}.
For example, when I change the value of 5 to 7, I have to restart my node.JS server and then refresh the page in order to get a 7. If I just refresh the page without restarting the server, I still get a 5.
Are you using nodemon?
If not do this:
npm i -D nodemon
than on your package.json do the following:
"scripts": {
"start": "nodemon LOCATION/OF/index.js"
}
now you have to run npm rum start to build you project.
On "LOCATION/OF/index.js" should be something like: nodemon src/index.js
Nodemon https://www.npmjs.com/package/nodemon
The problem is that nodemon doesn't watch for changes in .njk files.
You can use nodemon
By default, watching extensions for changes: js,json,md
Here's how to add .njk
Then run these commands:
npm install nodemon -g
nodemon app.js

express server starting react client

Until now, I have been using create-react-app for my projects, with the express-server and the react client each in their own folders.
However, I am now trying to avoid create-react-app in order to really understand how everything work under the hood. I am reading an Hacker Noon article that explains how to setup react with typescript and webpack. In this article they also have the express server at the root of the client which compiles everything itself:
const path = require('path'),
express = require('express'),
webpack = require('webpack'),
webpackConfig = require('./webpack.config.js'),
app = express(),
port = process.env.PORT || 3000;
app.listen(port, () => { console.log(`App is listening on port ${port}`) });
app.get('/', (req, res) => {
res.sendFile(path.resolve(__dirname, 'dist', 'index.html'));
});
let compiler = webpack(webpackConfig);
app.use(require('webpack-dev-middleware')(compiler, {
noInfo: true, publicPath: webpackConfig.output.publicPath, stats: { colors: true }
}));
app.use(require('webpack-hot-middleware')(compiler));
app.use(express.static(path.resolve(__dirname, 'dist')));
In the end, the start command looks like it:
"start": "npm run build && node server.js"
So I assume the client and the server start on the same port.
Why would you do such a thing? Are there any pros and cons?
It is true that this will allow your development to happen using the same server as express and that web pack will continuously update your dist/index.html file with whatever updates you make to your file. There's not too much of a disadvantage to this as this is just for development. But typically on prod you'll have a single built file that you will serve. And it will not web pack-dev-middleware to be running. Once you've built your server. For the purposes of production it might be possible that you'll only need static assets. But typically, even the server which serves mostly client files will potentially need a server if you want to do server side rendering and/or code splitting.
The command: "npm run build && node server.js" will run the bash/cmd commands into the terminal. npm run build is one step because of the use of && it will if that command succeeds, run the next command which is node server.js which is a strange command I would probably run node ./ (and put the server as index.js) or at least just write node server.
What I'd prefer to see in your package.json:
"start": "yarn build && node ./"
That would be possible if you mv server.js index.js (and npm i -g yarn).
Another thing to note, and look into is what the build step does.
Further Explanation:
The command runs the build step so check what your "build": key runs in your package.json.
This command will probably not exit with the code 1 (any exit code of a terminal process that is above 0 will result in an error and will not pass the &&).
Presumably, the build process described in the package.json will take all the javascript and CSS files and put them into the index.html file which will then be sent to the client side whenever someone access the '/' path.
After that succeeds, it will start the server that you put the code to above.
res.sendFile(path.resolve(__dirname, 'dist', 'index.html'));
will happen if anybody comes across the '/' path.

How to set up dev and API server from create-react-app?

I've started a new app with create-react-app, and ejected from that. I made a small express server as follows:
const express = require('express');
const app = express();
if(process.env.NODE_ENV === 'production') {
app.use(express.static('build'));
}
const port = process.env.PORT || 3000;
app.listen(port, () => {
console.log(`Server started at: http://localhost:${port}/`);
});
In package.json I've added a line, "proxy": http://localhost:3000", as well as switching the commands:
"scripts": {
"run": "npm-run-all -p watch-css start-js",
"start": "node server.js",
},
run used to be start.
However now of course when I run npm start and go to localhost:3000, I get Cannot GET /. I need this server to receive and return local API calls I'll be making from my app, but I also want it to run a hot-reloading dev server just like the old npm start (now npm run) command did. How do I do this?
Some time ago I made a fork of the create-react-app repository adding webpack watch option because of this same reason. It might help you.
Just to add more info, I really invested time looking on how to get webpackdevserver to build the "bundle.js", and found that it is not possible because it loads the bundle into memory but doesn't persist it, so the file is never created. The only way available is the webpack watch option but, I don't understand why the create-react-app team can't add it to the repo, it's a really requested feature, and there are more forks than mine that solves this issue. So, you have three options:
Use the proxy server in package.json (if it works)
Make your own fork and add the watch option, or use an existing one
Don't use create-react-app

how to compile the node.js itself

I couldnt find answer for this question.So that..for example
app.js
//express require
app.get("/test",function(req,res) {
res.send("hello world");
});
app.listen(3000)
when we work it via "node app.js".. We see "hello world" we requested http://ip:3000/test on browser .
but when we changed file, for example
//express require
app.get("/test",function(req,res) {
res.send("hello world 2");
});
app.listen(3000);
when we refreshed to browser.. we still see "hello world"...because we does not "node app.js command"
well!! but why????
when we worked "node app.js" command on console..what does node work for this?
Actually node doesn't refreshes the content until you restart the server. So, just restart the server after changing the content.
You can use --watch to watch for the changes automatically restart the server if content is changed.

node.js express socket.io port 3000 in use

I've been following this(http://socket.io/get-started/chat/) tutorial on how to make a simple chat application using socket.io.
I tried to however use Express to create it and I was wondering why port 3000 is already in use? The code below will not work unless I change the port number.
/* Make the http server listen on port 3000. */
http.listen(3000, function(){
console.log('listening on *:3000');
});
Does express use the port to do other things like routing or something?
Is there a simple way to find what is happening on that port?
I may also be doing something dodgy with my require things:
var express = require('express');
var app = require('express')();
var http = require('http').Server(app);
var router = express.Router();
var io = require('socket.io')(http);
Thanks.
I ran into this problem too and I solved it by this:
Do not use npm start to start your web app
Use node app.js instead
Try running:
netstat -anp tcp | grep 3000
This should show you the name of the process that is using port 3000. Here's another issue on StackOverflow that covers this issue in more depth.
One of the best way to do this during the development would be through IDE where you can do comprehensive debugging and step through the code.
If you are using WebStorm, this works.
From run configurations -> Edit Configurations -> Nods.js and add the app.js as the node parameter. See below arrow in the screenshots for more details.
I resolved the same problem with an express app doing this:
Edit the file "yourap/bin/www"
find the line :
var port = normalizePort(process.env.PORT || '3000');
replace it by:
var port = normalizePort('XXXX');
where XXXX is the port number you want to use
Then youre free to do npm start! xD
I had (forgotten that I had) previously installed ntop, which by default also uses port 3000, and was therefore getting the same error as described here.
As others have mentioned, use netstat or lsof to find the offending service (and prefix the command with sudo, to get the correct process name):
sudo lsof -P | grep ':3000'
- or -
sudo netstat -anp tcp | grep 3000
On Ubuntu, the service is disabled with (simply):
service ntop stop
Similar to answer above to not use npm start.
I was using nodemon and with expressjs and expressjs generator. I was using nodemon to execute npm start, while npm start itself execute node ./NodeApp/bin/www
So i edited to make nodemon to execute node ./NodeApp/bin/www by itself and that error go away.
Conclusion
Before
package.json
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1",
"start": "node ./NodeApp/bin/www",
"build": "webpack --watch",
"dev": "nodemon --exec npm start"
},
After
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1",
"build": "webpack --watch",
"dev": "nodemon --exec node ./NodeApp/bin/www"
},
So now I run my sever with npm run dev and no more errors.
for me helps to make use 3000 || 3333, and it's fix the issue
I solved it by this:
npm install shelljs
and add code for kill nodejs process before start listen port
var shell = require('shelljs');
shell.exec("pkill nodejs");
shell.exec("pkill node");
/* Make the http server listen on port 3000. */
http.listen(3000, function(){
console.log('listening on *:3000');
});

Resources