How can I add live-reload to my nodejs server

2020-02-04 20:30发布

This is how can i run my server nodejs , i need to liverealord my server when i make changes to the code in the front-end dev

"start": "node server.js"

7条回答
你好瞎i
2楼-- · 2020-02-04 20:46

Restarting server is one thing, refreshing browser is another thing. For server watching I use nodemon. Nodemon can see when changes occur in any types of files. But nodemon cannot refresh browser page. For this I use browser sync.

I use both in gulp.

So, dependencies from package.json to make it work:

"devDependencies": {
"browser-sync": "^2.24.5",
"gulp": "^3.9.1",
"gulp-nodemon": "^2.2.1"
}

In server file (my server is in ./bin/www, yours can be in server.js, app.js or elsewhere), express server listens to port 3001.

var port = normalizePort(process.env.PORT || '3001');
var server = http.createServer(app);
server.listen(port);

Next thing is to run nodemon and browser sync in gulp. Full contents of gulpfile.js

var gulp = require('gulp');
var nodemon = require('gulp-nodemon');
var browserSync = require('browser-sync').create();

gulp.task('gulp_nodemon', function() {
  nodemon({
    script: './bin/www', //this is where my express server is
    ext: 'js html css', //nodemon watches *.js, *.html and *.css files
    env: { 'NODE_ENV': 'development' }
  });
});

gulp.task('sync', function() {
  browserSync.init({
    port: 3002, //this can be any port, it will show our app
    proxy: 'http://localhost:3001/', //this is the port where express server works
    ui: { port: 3003 }, //UI, can be any port
    reloadDelay: 1000 //Important, otherwise syncing will not work
  });
  gulp.watch(['./**/*.js', './**/*.html', './**/*.css']).on("change", browserSync.reload);
});

gulp.task('default', ['gulp_nodemon', 'sync']);

When running gulp in terminal, it will start watching server as well as refreshing browser on change in any files.

Although we specify port 3001 in express server, our app will be working on port 3002, as we write in browser-sync. 3001 will be used as proxy.

查看更多
一夜七次
3楼-- · 2020-02-04 20:52

An example from my setup:

livereload.js (so this would be your server.js, of course only use the parts related to livereload, no need to replace your development server)

const path = require('path');
const fs = require('fs');

const livereload = require('livereload');
const lrserver = livereload.createServer();

const compiled = path.join( __dirname, "dist");
lrserver.watch( compiled ); 

const connect = require('connect');
const stat = require('serve-static');

const server = connect();
server.use( stat( compiled ));

server.listen( 3033 );

console.log( 'Dev server on localhost:3033' );

It actually starts two servers on localhost: the livereload server listening on :35729 and a static file server on :3033.

Livereload observes the dist directory which contains the compiled files (js, css, html). You need to add this snippet to every HTML page that should reload:

<script>
 document.write('<script src="http://' + (location.host || 'localhost').split(':')[0] +
                ':35729/livereload.js?snipver=1"></' + 'script>');
</script>

If you don't transpile/compile/preprocess your js/css/html code (i.e. you directly edit the files that are served) then observe the source directory and you're done. Otherwise you need a task that watches the source directory for changes and compiles to the dist directory which is observed by livereload :)

Relevant parts of my package.json:

"scripts": {
    "build": "npm run build:js && npm run build:css",
    "prewatch": "node livereload.js &",
    "watch": "node ./node_modules/watch-run/bin/watch -p './src/**' npm run build",
  },
"devDependencies": {
    "connect": "^3.6.2",
    "livereload": "^0.6.2",
    "serve-static": "^1.12.3",
    "watch-run": "^1.2.5"
  }

$ npm run watch builds the project and starts the livereload + static file servers. (the build:* tasks omitted for brevity).

查看更多
在下西门庆
4楼-- · 2020-02-04 20:52

Use the npm package called livereload.

Use it in conjunction with nodemon so both client side and server side work flawlessly.

npm install livereload nodemon --save

--save-dev. I know, I know!

Add browser extension. Available for Safari, Firefox, and Google Chrome. Get them here.

Make sure to have this scripts inside package.json.

  "scripts": {
"start": "nodemon server.js && livereload"

}

server.js is my entry point.

Inside the server.js add the following:

const livereload = require('livereload');
const reload = livereload.createServer();
reload.watch(__dirname + "/server.js");

server.js is the file I want livereload to watch. You can add any directory instead of a file as well.

reload.watch(__dirname + "/public");

In terminal: npm start

Click on the extension icon in the browser to connect.

You can also use livereload and nodemon separately in different terminals.

"scripts": {
    "start": "nodemon server.js",
    "livereload": "livereload"
  }

npm start

npm livereload

npm livereload -p PORT_NUMBER if default is port is already used.

Update: sometimes it doesn't work on saving once. A couple more of Ctrl+S reloads again and makes the changes. I don't know if this is a browser caching issue or package issue.

查看更多
▲ chillily
5楼-- · 2020-02-04 20:57

first:

npm install -g nodemon

next add a script line to your package.json

"live": "nodemon server.js" 

now when you npm live it'll live reload

for more details see https://github.com/remy/nodemon

update if live page reload is also needed

npm install -g livereload
livereload . -w 1000 -d

for more details see https://github.com/napcs/node-livereload

查看更多
混吃等死
6楼-- · 2020-02-04 20:59

If grunt is used, there is a npm package grunt-contrib-watch for live reloading.

Check out another one called grunt-express-server that can work together.

查看更多
别忘想泡老子
7楼-- · 2020-02-04 21:03
npm install browser-refresh -g

and add your main js

 if (process.send) {
     process.send('online');
 }

for example

app.listen(port, function() {
    console.log('Listening on port %d', port);

    if (process.send) {
        process.send('online');
    }
});

and add your index page before body close tag.

<script src="{process.env.BROWSER_REFRESH_URL}"></script>

and start your server on termial instead node server.js

browser-refresh server.js
查看更多
登录 后发表回答