What is the difference between nodemon and live-server? - node.js

Can someone help me understand the difference between npm packages nodemon and live-server as they both reload the server and listen for changes?

They serve two different purposes.
Nodemon will restart a Node application when file changes in a directory are detected.
Live-server on the other hand, will refresh your browser when changes are detected to any supported file types (e.g. HTML, JS, CSS). It also enables Ajax requests when you are working locally — these don't normally work with the file:// protocol.
Nodemon
To see this in action, let's create a simple Node server.
First, create a my-app directory, change into it, create a package.json file and a file named server.js. On a 'nix system, like so:
mkdir my-app
cd my-app
npm init -y
touch server.js
Then in server.js add:
const http = require('http');
const server = http.createServer(function (request, response) {
response.writeHead(200, {"Content-Type": "text/plain"});
response.end("Hello, World!\n");
});
server.listen(8000);
console.log("Server running at http://127.0.0.1:8000/");
Now, if you run node server.js, and visit http://127.0.0.1:8000/ in your browser, you will see a "Hello, World!" message.
If you edit server.js, for example to change the message to "Goodbye, World!", then refresh your browser, you will still see the ooriginal "Hello, World!" message.
To see the changes, you have to stop the application (with Ctrl + C), then restart it (with node server.js), then refresh your browser.
What nodemon does, is to wrap your Node application to automate this step of manually stopping and restarting the application.
Install it as a dev dependency:
npm i -D nodemon
And start your application like so:
./node_modules/.bin/nodemon server.js
Now when you make changes to server.js, nodemon will detect this automatically, meaning that all you need to is refresh your browser to see them — you avoid the stop/starting of the application.
Live-server
What live-server does on the other hand is quite different. You should install it globally:
npm install -g live-server
then when you start it in a directory, it will attempt to serve up an index.html file if one exists (otherwise it will display the directory's contents).
Staying in the my-app directory, create an index.html file:
touch index.html
Then add the following content:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<title>Test</title>
<style></style>
</head>
<body>
<p>Hello, World!</p>
<script></script>
</body>
</html>
Start live-server, by entering live-server in a terminal window and http://127.0.0.1:8080 should open in your browser.
Now try changing the message in the HTML file, or adding some styles or some JavaScript. When you make any of these changes and save, the browser will refresh and you will see these changes in your page.
This in itself is very practical, but nothing you couldn't do by refreshing the browser manually. Where a package like this becomes indispensable is when you make an Ajax request, include a file without using a protocol, or do anything else that would be blocked by the browser's security policy if you were to open an HTML file directly.

Related

Express can't find Webpack bundle

So I've been configuring a MERN app with a main package that runs an Express server, and a client folder which contains the React front end and has its own package. To test the client I've been using webpack-dev-server to run an HTML file within the client/public folder that links a Webpack bundle in a dist folder. The HTML file:
<!DOCTYPE html>
<html>
<head>
<title>React Config</title>
</head>
<body>
<div id="root"></div>
<script src="../dist/bundle.js"></script>
</body>
</html>
The relative path for the bundle is correct, and it works fine using WDS. However, when I try to serve this file via my Express server, I get a 404 error for the bundle file. In my server.js:
app.use(express.static('client'));
const appPage = path.join(__dirname, './client/public/index.html');
app.get('/', function(req, res) {
res.sendFile(appPage);
});
This does serve the HTML file correctly, but when I navigate to the local server it's trying to find bundle.js at http://localhost:3000/dist/bundle.js, instead of http://localhost:3000/client/dist/bundle.js. Furthermore, even when I change the path in the HTML to point to the right location, it 404's anyway.
So 2 questions:
1) How can I configure the paths for the Webpack bundle to be accessible both from WDS run within the client folder and from my Express server in the main package?
2) Why is the bundle not being found by Express even when I alter the path to be correct? I've included the entire client folder as static for the server.
You should not use webpack-dev-server for production, webpack-dev-server not build the index.html file, webpack-dev-server is only for developers.
You can use this command to build it:
webpack --config ./webpack.prod.js --mode production

npm live-server not auto-reloading

I have tried to work on the live server, installed a node package called live-server by using this command: npm install -g live-server
It worked fine, installed successfully and run live-server by live-server command.
Whenever I change my code and save on code editor, the browser won't refresh automatically.
Here is my package.json file:
"name": "nodejs",
"version": "1.0.0",
"description": "",
"main": "app.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"author": "Abul Khoyer",
"license": "ISC"
}
I had the same problem as you and managed to get it working by making sure that the .html-file was properly formatted. I.e. like this:
<!DOCTYPE html>
<html>
<body>
<h1>Script tester!</h1>
<script type="text/javascript" src="script.js"></script>
</body>
</html>
You need to add this code:
for
Usage from node
Example:
var liveServer = require("live-server");
var params = {
port: 8181, // Set the server port. Defaults to 8080.
host: "0.0.0.0", // Set the address to bind to. Defaults to 0.0.0.0 or process.env.IP.
root: "/public", // Set root directory that's being served. Defaults to cwd.
open: false, // When false, it won't load your browser by default.
ignore: 'scss,my/templates', // comma-separated string for paths to ignore
file: "index.html", // When set, serve this file for every 404 (useful for single-page applications)
wait: 1000, // Waits for all changes, before reloading. Defaults to 0 sec.
mount: [['/components', './node_modules']], // Mount a directory to a route.
logLevel: 2, // 0 = errors only, 1 = some, 2 = lots
middleware: [function(req, res, next) { next(); }] // Takes an array of Connect-compatible middleware that are injected into the server middleware stack
};
liveServer.start(params);
Or else you can add a file .live-server.json :
If that exists it will be loaded and used as default options for live-server on the command line.
For more details see: https://www.npmjs.com/package/live-server
Use NPM To Install A Package Called PM2.
NPM is a package manager that you will use to install frameworks and libraries to use with your Node.js applications. NPM was installed with Node.js. PM2 is a sweet little tool that is going to solve two problems for you:
It is going to keep your site up by restarting the application if it crashes. These crashes should NOT happen, but it is good know that PM2 has your back. (Some people may be aware of Forever.js, another tool that is used to keep node based sites running - I think you will find that PM2 has a lot to offer.)
It is going to help you by restarting your node application as a service every time you restart the server. Some of use know of other ways to do this, but pm2 makes it easier, and it has some added flexibility.
Install PM2 by typing thr following at the command line:
sudo npm install pm2 -g
You can follow this line to setup Nodejs production environment:
https://www.digitalocean.com/community/tutorials/how-to-use-pm2-to-setup-a-node-js-production-environment-on-an-ubuntu-vps
If you're working on Windows 10 like myself, it's likely that your directory name is too long like this:
C:\Users\Del\Documents\Web Development Works\JS
Exercises[books]\Learning JavaScript\lj
Just try to move your directory to Desktop so it will be much shorter like this:
C:\Users\Del\Desktop\lj
In my case, the auto-reload of live-server is working after I move my directory to Desktop
Check your script tag in html file.
don't close your tag as empty element like this < /> .
This was preventing my browser to load page automatically.
close it properly <> .
I had the same problem as you, I solve that with check two items :
First, check your script tag in your HTML file !
<script type="text/javascript" src="script.js"></script>
if you try first step and it dosen't work again, move(copy/cut) your project's file in "DESKTOP", close Browser, VScode work space (command+K+F) and VScode (command+Q), and try again !

Can i use node as webserver for html app?

I'm sorry to ask such a simple question. I've been sent files by someone, an index.html file which pulls in a js file within script tags. I have to start a webserver to get through authentication and view the files (am in dev).
In my CLI i have navigated to the directory containing index.html. I have checked with node -v that I have it installed globally (yes, v 8.6). I've run the simple command node and checked my browser at http://localhost:3000 and a few other ports but get no joy. I've also tried node index.html but CLI throws an error.
How do i start the webserver? All the examples online tell me to build a .js file, but this is not an option.
Steps to set up a node web server
Create the route folder from your local machine.
Go to the command prompt from the project root path.
Install express using the command npm install express
Create server.js file
create the folder wwww and create the Index.html inside it.
server.js
var express = require('express');
var app = express();
app.use(express.static(__dirname + '/www'));
app.listen('3000');
console.log('working on 3000');
Index.html
<!doctype html
<html>
<head>
<title> my local server </title>
</head>
<body>
<h1> server working </h1>
<p> just put your html,css, js files here and it work on your own local nodejs server </p>
</body>
</html>
Go to the project root path and take the command prompt, then start the server by running the command node server.js
Then go to the browser and run the url localhost:3000.
Now you can see the html page will render on your browser.
Since you don't want to build a backend but just an http server.
I would propose to use an npm package that do just what you need:
Open a console
npm install http-server -g
Go to your "index.html" folder (in the console) then type:
http-server
Then reach your content in your browser at this address:
http://localhost:8080
Documentation here:
https://www.npmjs.com/package/http-server
Yes, this is possible.
A very simple example of how to do this would be to create file, let's call it app.js and put this in it:
const http = require('http'), // to listen to http requests
fs = require('fs'); // to read from the filesystem
const app = http.createServer((req,res) => {
// status should be 'ok'
res.writeHead(200);
// read index.html from the filesystem,
// and return in the body of the response
res.end(fs.readFileSync("index.html"));
});
app.listen(3000); // listen on 3000
Now, run node app.js
Browse to http://localhost:3000
There's loads of other npm packages that will help you out do this, but this is the simplest 'pure node' example to literally read index.html and serve it back as the response.
Its very easy to start a server using node js
Create a server.js file,
const http = require('http')
const fs = require('fs');
http.createServer(function (req, res) {
fs.readFile('index.html', function(err, data) {
res.writeHead(200, {'Content-Type': 'text/html'});
res.write(data);
res.end();
});
}).listen(3000);
Run node server.js
Here is a reference
This will even solve your backslash issue by this

Installed Node + vue-cli on AWS. But get a blank page?

Ok, learning here. Installed the default vue-cli app on AWS. I do a npm run build. When I launch the default index.html I'm served a blank page. If I go into dist, there is another index.html, that serves links to js files, but still a blank page.
I'm guessing webpack wants me to launch an index.html, but don't see how I can hit that with a browser. No errors anywhere. But no Hello World either. thanks for help.
What I'm seeing in the browser:
<!DOCTYPE html><html><head><meta charset=utf-8><title>hello-world</title><link href=/static/css/app.87e65e7c83fb67c04e58d4461a7fd8e8.css rel=stylesheet></head><body><div id=app></div><script type=text/javascript src=/static/js/manifest.fa7eecfb52900d1cfb0a.js></script><script type=text/javascript src=/static/js/vendor.9baeef453ba99a70f46a.js></script><script type=text/javascript src=/static/js/app.cdfbb21001bbc43de4bc.js></script></body></html>
When you npm run build Webpack should produce an index.html file along with a static/ directory that contains all of your javascript and css. The link to static/ is an absolute link (i.e. http://example.org/static). When you try to open index.html as a file, the browser will look for the /static/ folder on the root of your file system, which of course it won't find.
To run it locally you need to fire up an http server locally. One option is to cd into the directory with a terminal app and run python -m http.server. Then go to http://localhost:8000/. That should work because the root of the directory tree will be the folder from where you are serving it.
Getting it running on AWS S3 will be a matter of making sure you get the static directory in the right place and get the links pointing to it. Hard to say exactly how without knowing details of how you are organizing the site in your bucket.
You can change how the static folder is saved in the webpack config if you need to: https://vuejs-templates.github.io/webpack/static.html
You will find a folder named /dist in your project directory.Just point the index.html file within the /dist directory and rest will work fine I think. I have just done that and it's working fine.
Hope it will work.
Thanks.

Have nodeJS refresh angularjs2 files without re-compiling with npm start

I am using angularjs2 with typescript in the client side and nodejs and express in the back-end, and every time i make changes to my client side files(.ts & .html) while running my node server on port 3000 i don't get the saved changes,so i have to run npm start for the ng-2 lite-server so that it like refreshes to get the changes, I am not sure whether i need a single module loader like SystemJS, which is the one i am using with ng2, or i need another systemjs required in my server so to get changes after saving.
In my server file i have
app.use(express.static(path.join(__dirname, 'client')));
that loads the static files, and which loads the index.html file that has the lines which i learn that they load application modules for ng2
<script src="systemjs.config.js"></script>
<script>
System.import('app').catch(function(err){ console.error(err); });
</script>
Since my server loads the index.html which contains the above code, im expecting nodejs and express to load the updated files accordingly, or is it because nodejs uses commonJS instead of system?
Is this the right way to do it or there is a better integration method for ng2 and nodejs?
What are the efficient options that are there in this aspect?
I'd suggest using pm2 to run your node server. The --watch flag will restart node (non-gracefully but quickly). If your Angular app is inside the node app folder then node will restart given just the flag, if it's outside that then you can pass a specified path to the --watch flag.
pm2 is a Production quality tool for Node, and works great locally too.
Details: http://pm2.keymetrics.io/docs/usage/watch-and-restart/
Example cmd: pm2 start index.js --watch

Resources