Code Monkey home page Code Monkey logo

node-livereload's Introduction

node-livereload

Build status

An implementation of the LiveReload server in Node.js. It's an alternative to the graphical http://livereload.com/ application, which monitors files for changes and reloads your web browser.

Usage

You can use this by using the official browser extension or by adding JavaScript code to your page.

Method 1: Use Browser Extension

Install the LiveReload browser plugins by visiting http://help.livereload.com/kb/general-use/browser-extensions.

Note: Only Google Chrome supports viewing file:/// URLS, and you have to specifically enable it. If you are using other browsers and want to use file:/// URLs, add the JS code to the page as shown in the next section.

Once you have the plugin installed, start livereload. Then, in the browser, click the LiveReload icon to connect the browser to the server.

Method 2: Add code to page

Add this code:

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

Note: If you are using a different port other than 35729 you will need to change the above script.

Running LiveReload

You can run LiveReload two ways: using the CLI application or by writing your own server using the API.

Method 1: Using the Command line Interface

To use livereload from the command line:

$ npm install -g livereload
$ livereload [path] [options]

To watch files in the current directory for changes and use the default extensions, run this command:

$ livereload

To watch files in another directory, specify its path:

$ livereload ~/website

The commandline options are

  • -p or --port to specify the listening port
  • -d or --debug to show debug messages when the browser reloads.
  • -e or --exts to specify extentions that you want to observe. Example: -e 'jade,scss'. Removes the default extensions.
  • -ee or --extraExts to include additional extentions that you want to observe. Example: -ee 'jade,scss'.
  • -x or --exclusions to specify additional exclusion patterns. Example: -x html, images/.
  • -u or --usepolling to poll for file system changes. Set this to true to successfully watch files over a network.
  • -w or --wait to add a delay (in miliseconds) between when livereload detects a change to the filesystem and when it notifies the browser.
  • -op or --originalpath to set a URL you use for development, e.g 'http:/domain.com', then LiveReload will proxy this url to local path.

For example, to use a wait time and turn on debugging so you can see messages in your terminal, execute livereload like this:

$ livereload -w 1000 -d

To turn on debugging and tell Livereload to only look at HTML files in the public directory, run it like this:

$ livereload public/ -e 'html'

The file path can be at any place in the arguments. For example, you can put it at the end if you wish:

$ livereload -e 'html' public/

Finally, you can tell LiveReload to refresh the browser when specific filenames change. This is useful when there are files that don't have extensions, or when you want to exclude all HTML files except for index.html throughout the project. Use the -f or --filesToReload option:

$ livereload -f 'index.html' public/

All changes to index.html in any subdirectory will cause LiveReload to send the reload message.

Option 2: From within your own project

To use the api within a project:

$ npm install livereload --save

Then, create a server and fire it up.

var livereload = require('livereload');
var server = livereload.createServer();
server.watch(__dirname + "/public");

You can also use this with a Connect server. Here's an example of a simple server using connect and a few other modules just to give you an idea:

var connect  = require('connect');
var compiler = require('connect-compiler');
var static = require('serve-static');

var server = connect();

server.use(
  compiler({
      enabled : [ 'coffee', 'uglify' ],
      src     : 'src',
      dest    : 'public'
  })
);

server.use(  static(__dirname + '/public'));

server.listen(3000);

var livereload = require('livereload');
var lrserver = livereload.createServer();
lrserver.watch(__dirname + "/public");

You can then start up the server which will listen on port 3000.

Server API

The createServer() method accepts two arguments.

The first are some configuration options, passed as a JavaScript object:

  • https is an optional object of options to be passed to https.createServer (if not provided, http.createServer is used instead)
  • port is the listening port. It defaults to 35729 which is what the LiveReload extensions use currently.
  • exts is an array of extensions you want to observe. This overrides the default extensions of [html, css, js, png, gif, jpg, php, php5, py, rb, erb, coffee].
  • extraExts is an array of extensions you want to observe. The default extensions are [html, css, js, png, gif, jpg, php, php5, py, rb, erb, coffee].
  • applyCSSLive tells LiveReload to reload CSS files in the background instead of refreshing the page. The default for this is true.
  • applyImgLive tells LiveReload to reload image files in the background instead of refreshing the page. The default for this is true. Namely for these extensions: jpg, jpeg, png, gif
  • exclusions lets you specify files to ignore. By default, this includes .git/, .svn/, and .hg/
  • originalPath Set URL you use for development, e.g 'http:/domain.com', then LiveReload will proxy this url to local path.
  • overrideURL lets you specify a different host for CSS files. This lets you edit local CSS files but view a live site. See http://feedback.livereload.com/knowledgebase/articles/86220-preview-css-changes-against-a-live-site-then-uplo for details.
  • usePolling Poll for file system changes. Set this to true to successfully watch files over a network.
  • delay add a delay (in miliseconds) between when livereload detects a change to the filesystem and when it notifies the browser. Useful if the browser is reloading/refreshing before a file has been compiled, for example, by browserify.
  • noListen Pass as true to indicate that the websocket server should not be started automatically. (useful if you want to start it yourself later)

The second argument is an optional callback that will be sent to the LiveReload server and called for the listening event. (ie: when the server is ready to start accepting connections)

Watching multiple paths:

Passing an array of paths or glob patterns will allow you to watch multiple directories. All directories have the same configuration options.

server.watch([__dirname + "/js", __dirname + "/css"]);

Command line:

$ livereload "path1, path2, path3"

Using the originalPath option

You can map local CSS files to a remote URL. If your HTML file specifies live CSS files at example.com like this:

<!-- html -->
<head>
  <link rel="stylesheet" href="http://domain.com/css/style.css">
</head>

Then you can tell livereload to substitute a local CSS file instead:

// server.js
var server = livereload.createServer({
    originalPath: "http://domain.com"
});
server.watch('/User/Workspace/test');

Then run the server:

$ node server.js

When /User/Workspace/test/css/style.css is modified, the stylesheet will be reloaded on the page.

Troubleshooting

The browser extension doesn't connect.

If you're using file:/// urls, make sure the browser extension is configured to access local files. Alternatively, embed the livereload.js script on your page as shown in this README.

When I change the HTML page I'm working on, the browser refreshes and tells me the file isn't found.

Your editor is most likely using a swapfile, and when you save, there's a split second where the existing file is deleted from the file system before the swap file is saved in its place. This happens with Vim. You can disable swapfiles in your editor, or you can add a slight delay to Livereload using the -w option on the command line.

Developing livereload

This library is implemented in CoffeeScript 1.x. It may eventually be converted to JavaScript, but because there are many projects that depend on this library, the conversion isn't a priority.

To build the distributable versions, run npm run build.

Run npm test to run the test suite.

Contributing

Contributions welcome, but remember that this library is meant to be small and serve its intended purpose only. Before submitting a pull request, open a new issue to discuss your feature or bug. Please check all open and closed issues.

When submitting code, please keep commits small, and do not modify the README file. Commit both the Coffee and JS files.

Changelog

0.9.3

  • CLI: Fix multiple path parsing bug.

0.9.2

  • Server: Added filesToReload option to specify a list of filenames that should trigger the reload, rather than relying on extensions alone.
  • CLI: You can use the -f or --filesToReload option with the command line tool to specifiy filenames that should trigger a reload.
  • CLI: The file path is no longer fixed to a specific position in the arguments list
  • CLI: You no longer need to specify the file path when using additional arguments
  • CLI: You can use the -op or --originalpath option with the command line tool instead of writing your own server.
  • CLI: The help screen displays more accurate option descriptions.
  • Tests: Added more specific tests to ensure that refresh is called in various scenarios.
  • Other: Removed Cakefile as Cake is no longer needed. Use npm run tests and npm run build instead.
  • Dependencies: Updated chokidar dependency to 3.5.1
  • Dependencies: Updated livereload-js dependency to 3.3.1
  • Dependencies: Updated ws dependency to 7.4.3

0.9.1

  • Fix issue with livereload.js not resolving properly on some projects (caseywebdev)
  • Update license to newer style to suppress "no license" messages.
  • Update test scripts to handle compilers properly, suppressing the deprecation notice
  • Deprecating the cake tasks for building the project.

0.9.0

  • Serve Livereload client library from an NPM dependency instead of copying the code into the project - smhg
  • Update Chokidar to 3.3.0 which improves performance and reduces CPU load.

0.8.2

  • Fix regression in 0.8.1 where broadcasting failed due to incompatibility between arrays and sets
  • Add debug message when broadcasting to each socket
  • Add debug message for the input message from clients

0.8.1

  • Update ws dependency to v6.2.1 to close security vulnerability

0.8.0

  • Update bundled Livereload.js file to v3.0.0
  • Update deps to close security vulnerabilities

0.7.0

  • Updates bundled Livereload.js file to v2.3.0 to fix console error.
  • BREAKING CHANGE: The exts and e options now replace the default extensions.
  • Adds the extraExts and ee options to preserve the old behavior of adding extensions to watch.
  • You can now use server.on 'error' in your code to catch the "port in use" message gracefully. The CLI now handles this nicely as well.

0.6.3

  • Updated to use Chokidar 1.7, which hopefully fixes some memory issues.
  • BUGFIX: Check to see if a watcher object is actually defined before attempting to close.
  • Added deprecation warning for exts option. In the next version, extensions you specify on the command line will OVERRIDE the default extensions. We'll add a new option for adding your exts to the defaults.
  • Modified CLI so it trims spaces from the extensions in the array, just in case you put spaces between the commas.

0.6.2

  • CLI now properly splits extension list. Previous versions appended a blank entry to the list of extensions.
  • CLI now requires extensions to be comma separated instead of space separated.
  • Added extra debugging info (protocol version, watched directory, extensions, and exclusions).
  • Cleaned up some inconsistencies in the code.

0.6.1

  • Fix default exclusions regex

0.6.0

  • Implements LiveReload protocol v7 so browser plugins work again.
  • Removes support for protocol v6
  • Introduces noListen option
  • Introduces optional callback which will be invoked when the LiveReload server is listening

0.5.0

  • Updated ws library
  • Fix issues with exclusions
  • Allow watching multiple paths from CLI
  • Added delay option

0.4.1

  • Remove some bad JS code

0.4.0

  • Rewritten using Chokidar library and ws library
  • Added usePolling option
  • Added support for specifying additional extensions from the CLI

Older version history not kept.

License

Copyright (c) 2010-2021 Brian P. Hogan and Joshua Peek

Released under the MIT license. See LICENSE for details.

node-livereload's People

Contributors

ariunbayar avatar caseywebdev avatar dominicbarnes avatar epferrari avatar eugeneware avatar fracmak avatar hugojosefson avatar ismaail avatar jaymorrow avatar jeka-kiselyov avatar jleverenz avatar josh avatar jsonfry avatar kibertoad avatar leftium avatar napcs avatar nemodreamer avatar nv avatar offirmo avatar oklai avatar oliverxchen avatar raineorshine avatar shindakun avatar smhg avatar timhuff avatar tiye avatar veproza avatar wavded avatar xpressivecode avatar zemax avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar

node-livereload's Issues

Watch new files

whenever I create a new file on the folder I'm running live reload guard, the changes on that file does not trigger browser reload.
My workaround is to restart the guard
Is it possible to add the new files to the watch automatically?

Installation Error

Node version : 5.5.0
Npm version : 2.13.5

Hi,

When I want to install the package livereload npm install -g livereload, I have this kind of error :

gyp ERR! stack Error: 404 status code downloading 64-bit node.lib

Can you explain ?

Thanks

OverrideURL example

Hi,

Could you provide a simple example of what should be the expected input for the overrideURL option. Should the value be a boolean or an absolute path?

Cheer,
Phil

Error: not opened in WebSocket.js

Every now and then I get the following error in LiveReload.

info: livereload: Sending refresh to browser
/tmp/tmp.vYah8haBMV/livereload/node_modules/websocket.io/node_modules/ws/lib/WebSocket.js:175
    else throw new Error('not opened');
               ^
Error: not opened
    at WebSocket.send (/tmp/tmp.vYah8haBMV/livereload/node_modules/websocket.io/node_modules/ws/lib/WebSocket.js:175:16)
    at WebSocket.write (/tmp/tmp.vYah8haBMV/livereload/node_modules/websocket.io/lib/protocols/hybi.js:101:13)
    at WebSocket.Socket.send (/tmp/tmp.vYah8haBMV/livereload/node_modules/websocket.io/lib/socket.js:106:8)
    at Server.refresh (/tmp/tmp.vYah8haBMV/livereload/lib/livereload.js:179:30)

how config watch more dir

It's not issue, just a question
var livereload = require('livereload');
server = livereload.createServer();
server.watch(__dirname + "/public");

How to make addtion for watch /view dir ?

does not work with absolute paths

./node_modules/.bin/livereload  public # relative path works
./node_modules/.bin/livereload  /foo/bar/baz/public # absolute path does not work

absolute paths don't seem to work here, is my observation correct?
My assumption is that you are not checking if the path is absolute before appending the current working directory.

Please do something like this:

const path = require('path');

function resolve(p){
  return path.isAbsolute(p) ? p : path.resolve(process.cwd() + '/' + p)
}

How to setup?

Hi. I have installed livereload in nodejs and now I'm straggling with this code:
Where shell I add it?
livereload = require('livereload');
server = livereload.createServer();
server.watch(__dirname + "/public");

Can you explain please.

npm scripts example

I try to liveReload from a npm scripts, but I can not get it:

I installed liveReload globally and locally. Here is the script:

"watch": "onchange '/src/**/*.*' -- npm run dev & liveReload http://localhost"

and

$ npm run watch 

Now the browser extension is watching but the page does not reload onchange.

What am I doing wrong here?

thanks

https

If I use https, must I use the .js file instead of the browser extension ?

This is the piece of the script to start the server --

server = require('livereload').createServer( {
    https: { 
        key: fs.readFileSync( process.env.SSLKEY ),
        cert: fs.readFileSync( process.env.SSLCERT )
    },
    originalPath: https://${process.env.DOMAIN}.com
} )

The consolelogs from Chrome
livereload.js?ext=Chrome&extver=2.1.0&host=127.0.0.1&port=35729:74 Mixed Content: The page at 'https://localhost:1337/home' was loaded over HTTPS, but attempted to connect to the insecure WebSocket endpoint 'ws://127.0.0.1:35729/livereload'. This request has been blocked; this endpoint must be available over WSS.

Uncaught SecurityError: Failed to construct 'WebSocket': An insecure WebSocket connection may not be initiated from a page loaded over HTTPS

Does not work in command line when options are specified before path

What version are you using?

0.6.0

I run livereload in command line:

livereload --port 4444 public/

And include script to page:

<script src="//localhost:4444/livereload.js?snipver=1"></script>

Expected result

Should apply changes (reload page)

Actual result

WS connection is established (I see three messages), but server does not notify client about changes.

When I change arguments order (put path first)

livereload public/ --port 4444

livereload starts to work as expected:

{"command":"reload","path":"/home/dmitry/dev/public/styles/styles.css","liveCSS":true,"originalPath":"","overrideURL":""}

installation error

root@vps58220:~# npm install -g livereload
npm http GET https://registry.npmjs.org/livereload
npm http 404 https://registry.npmjs.org/livereload
npm ERR! TypeError: Cannot read property 'latest' of undefined
npm ERR!     at next (/usr/local/lib/node_modules/npm/lib/cache.js:744:35)
npm ERR!     at /usr/local/lib/node_modules/npm/lib/cache.js:732:5
npm ERR!     at saved (/usr/local/lib/node_modules/npm/node_modules/npm-registry-client/lib/get.js:148:7)
npm ERR!     at /usr/local/lib/node_modules/npm/node_modules/graceful-fs/polyfills.js:133:7
npm ERR!     at Object.oncomplete (fs.js:107:15)
npm ERR! If you need help, you may report this *entire* log,
npm ERR! including the npm and node versions, at:
npm ERR!     <http://github.com/npm/npm/issues>

npm ERR! System Linux 2.6.32-042stab084.14
npm ERR! command "/usr/local/bin/node" "/usr/local/bin/npm" "install" "-g" "livereload"
npm ERR! cwd /root
npm ERR! node -v v0.10.26
npm ERR! npm -v 1.4.3
npm ERR! type non_object_property_load
npm ERR! 
npm ERR! Additional logging details can be found in:
npm ERR!     /root/npm-debug.log
npm ERR! not ok code 0
root@vps58220:~# 

livereload doesn't trigger reload on change

I've created a test case here: https://github.com/dotnetCarpenter/livereload-test

I run ecstatic as web server with root in root/ and livereload watching root/css/
To run the test case locally you can just clone the repo and do npm i and then npm run testlivereload. Open your browser at localhost:8000 and you should see a message in the console:

Starting LiveReload v0.4.0 for [...]/livereload-test/root/css on port 35729.
Browser connected.
Browser URL: {"command":"hello","protocols":["http://livereload.com/protocols/official-6","http://livereload.com/protocols/official-7"],"ver":"2.0.8","snipver":"1"}

In the browser devtools I see that http://localhost:35729/livereload.js?snipver=1 is loaded but when I change the content in a.css the page does not get reloaded.

As a side note, running livereload with livereload root/css -d -e css fails with Unknown option: -e Try --help. -e | --exts is documented in the livereload README

list the "debug" option

While debugging #20, I had to figure out the debug option from the code, since it's not listed in the README.

It should, shouldn't it ?

Need to implement v7 protocol.

The v6 protocol is deprecated. Browser plugins only support the v7 protocol and we are not shipping a v7 compatible client or server.

I try to use HTTPS

Hi I am trying to use the command line but serve https instead of the default http
where do I put the :

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

const options = {
  key: fs.readFileSync('test/fixtures/keys/agent2-key.pem'),
  cert: fs.readFileSync('test/fixtures/keys/agent2-cert.pem')
};

https.createServer(options, (req, res)

thanks in advance... If I can just edit some files to point to the keys.

Manually triggering reload?

nodemon app takes a few seconds to restart the server but the live reload is triggered as soon as a file is changed. Is there a way to manually trigger the reload? I'm trying to use the nodemon restart event and manually trigger a reload(Not watching server files). Client files would be handled via args.

Allow for passing a callback to the server (for when it comes up)

It turns out that ws.Server() accepts a callback as the 2nd argument (after options) which is called after the server is up and ready to accept connections. It would be great to hook into this behavior via livereload.createServer(). (or, if #74 is accepted, then server.listen() should accept a callback parameter)

Support stream

I use fs.fs.createWriteStream to write files and node-livereload reload my files too early.
Chokidar change event fired before stream write is complete.

Failed to parse package.json data

I was trying to:

sudo npm install -g livereload

and got:

Failed to parse json
npm ERR! Unexpected end of input
npm ERR! File: /home/venkat/.npm/commander/0.6.1/package/package.json
npm ERR! Failed to parse package.json data.
npm ERR! package.json must be actual JSON, not just JavaScript.
npm ERR! 
npm ERR! This is not a bug in npm.
npm ERR! Tell the package author to fix their package.json file. JSON.parse

npm ERR! System Linux 3.13.0-38-generic
npm ERR! command "/usr/bin/nodejs" "/usr/bin/npm" "install" "-g" "livereload"
npm ERR! cwd /home/venkat
npm ERR! node -v v0.10.25
npm ERR! npm -v 1.3.10
npm ERR! file /home/venkat/.npm/commander/0.6.1/package/package.json
npm ERR! code EJSONPARSE
npm http 304 http://registry.npmjs.org/ms/0.6.2
npm http 304 http://registry.npmjs.org/options
npm http 304 http://registry.npmjs.org/tinycolor
npm ERR! 
npm ERR! Additional logging details can be found in:
npm ERR!     /home/venkat/npm-debug.log
npm ERR! not ok code 0

I am using

Ubuntu 14.04.1 LTS
node v0.10.25
npm 1.3.10

Thanks in advance!

ERR_CONNECTION_REFUSED http://localhost:35729/livereload.js?snipver=1

I added

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

to the bottom of my page as per the documentation and I get the following error in the Chrome developer console:

Failed to load resource: net::ERR_CONNECTION_REFUSED http://localhost:35729/livereload.js?snipver=1

I get this error both when using file:/// and with http-server running on localhost:8080. I've even used netstat to check if port 35729 is being used (it's not), and tried changing the port in the script tag, always get the same error.

If instead I run livereload . in the root directory of my site, I see

Starting LiveReload v0.4.1 for C:\Users\eric\workspace\Portfolio Sites\avertourism.com on port 35729.

in the terminal and nothing else. No error is shown but livereload still doesn't work. If I use Firefox instead of Chrome + the script tag approach, it doesn't show any error but livereload still doesn't work.

I am using Windows 10.

Upgrade 0.4.0 no longer working...

It just gets stuck. No errors are shown.

 ➔ livereload 
Starting LiveReload v0.4.0 for /home/atomi/gamma on port 35729
WebSocket connection to 'ws://127.0.0.1:35729/livereload' failed: Error in connection establishment: net::ERR_CONNECTION_REFUSED

edit: here is the install log

 ➔ npm install -g livereload
npm WARN optional dep failed, continuing [email protected]

> [email protected] install /usr/local/node-v4.2.2-linux-x64/lib/node_modules/livereload/node_modules/ws/node_modules/bufferutil
> node-gyp rebuild

make: Entering directory `/usr/local/node-v4.2.2-linux-x64/lib/node_modules/livereload/node_modules/ws/node_modules/bufferutil/build'
  CXX(target) Release/obj.target/bufferutil/src/bufferutil.o
  SOLINK_MODULE(target) Release/obj.target/bufferutil.node
  COPY Release/bufferutil.node
make: Leaving directory `/usr/local/node-v4.2.2-linux-x64/lib/node_modules/livereload/node_modules/ws/node_modules/bufferutil/build'

> [email protected] install /usr/local/node-v4.2.2-linux-x64/lib/node_modules/livereload/node_modules/ws/node_modules/utf-8-validate
> node-gyp rebuild

make: Entering directory `/usr/local/node-v4.2.2-linux-x64/lib/node_modules/livereload/node_modules/ws/node_modules/utf-8-validate/build'
  CXX(target) Release/obj.target/validation/src/validation.o
  SOLINK_MODULE(target) Release/obj.target/validation.node
  COPY Release/validation.node
make: Leaving directory `/usr/local/node-v4.2.2-linux-x64/lib/node_modules/livereload/node_modules/ws/node_modules/utf-8-validate/build'
/usr/local/node-v4.2.2-linux-x64/bin/livereload -> /usr/local/node-v4.2.2-linux-x64/lib/node_modules/livereload/bin/livereload.js
[email protected] /usr/local/node-v4.2.2-linux-x64/lib/node_modules/livereload
├── [email protected]
├── [email protected] ([email protected], [email protected], [email protected], [email protected], [email protected], [email protected], [email protected], [email protected], [email protected])
└── [email protected] ([email protected], [email protected], [email protected], [email protected])

Does livereload auto listen for changes?

I'm using this plugin with grunt watch and it works great. When I change a file that my grunt watch is watching it will cause the page to be reloaded successfully.

But I noticed that because you declare livereload to watch a directory and if you console out the server variable that it's in fact looking for a bunch of different files by default...

var livereload = require('livereload');
var server = livereload.createServer();
server.watch(__dirname);

console.log(server);

So does this mean that the plugin should automatically causing a reload if files are changed in the specified directory? As for me this isn't the case, it only fires via the grunt watch module. So if I edit a HTML file or CSS file, nothing happens...

Updating many files at the same time causes livereload to reload the files insanely many times

I have a gulp task that rebuilds all scss files when I'm changing the theme, this is currently resulting in 45 css files being generated in development environment. Problem is that livereload is reloading all files for just one file change, resulting in thousands of requests.

module.exports = function (watchDir)
{
    return function ()
    {
        var livereload = require('livereload');
        var server = livereload.createServer({
            originalPath: "http://localhost/mac"
        });
        return server.watch("wwwroot/css/");
    }
}

Refresh all when server starts

What version are you using? (Don't say latest. Be specific.)

0.5.0

Expected result

Refresh all browser views when the node server restarts.

Actual result

The livereload socket reconnects, but it doesn't refresh the page.

Why is this important?

Livereload works fine when I edit client-side files. However it would be just as useful when I have to edit and restart the node server. This use case happens almost as often. In my case, I have to reload all open browser views manually in order to re-initialize them (for example to establish further websocket connections).

Basically, I'm looking for a command to force the refresh of all browser views, so that I can call it on server start (and possibly on other occasions).

livereload resets folded lines in sublime text 3.

HI I have win 7/64bit, and I use sublime text 3 also 64 bits. When I save file, while there are folded lines it reopen them. This happens every time when I save file. It's a livereload plugin for chrome and I'm using gulp-livereload node module.

Callbacks (Feature Request)

What version are you using? (Don't say latest. Be specific.)

0.6.0

Expected result

I would expect LiveReload to be able to for a callback when a certain kind of extension was changed.

Example:

const liveReloadServer = liveReload.createServer({
	port: 35729,
        list: [{
            ext: '.md',
            callback: () => { doSomething(); }
       }]
}).watch(dir);

Actual result

N/A

Steps to reproduce issue

Use the code above.

Why is this important?

Flexibility.

kills chrome browser

I did some careful experimentation. Looks like the server side process will kill chrome if I start the process. Here is the script I am using:

#!/usr/bin/env bash

cd $(dirname "$0") &&

(kill -9 $(lsof -i:3050 -t) 2> /dev/null) || echo "server was not running" &&
#(kill -9 $(lsof -i:35729 -t) 2> /dev/null) || echo "live-reload was not running" &&

PUBLIC_DIR=$(cd $(dirname "$0") && pwd)/public

if [[ "${NODE_ENV}" == "development" ]]; then
     ./node_modules/.bin/livereload ${PUBLIC_DIR} &> logs/live-reload.log &  # run live reload in background
     ./node_modules/.bin/roodles $@ . # roodles is like nodemon, same thing
else
    echo " We aren't in development anymore Dorothy..."
    # etc etc
fi

at first I thought I was killing chrome with the following command

(kill -9 $(lsof -i:35729 -t) 2> /dev/null) || echo "live-reload was not running" &&

but I commented that line out as you can see, and it looks like chrome still gets killed by this module.

Can you please help me figure out if there is a way to prevent this module from killing my entire chrome browser and all the tabs? Otherwise it seems to be working fine.

thanks!

Regexes in defaultexclusions are incorrect

What version are you using?

livereload 0.6.0

Expected result

The default ignored directories (including .git) should be ignored by livereload.

Actual result

They are not ignored.

Note

I have a question about this particular commit, which I thnk is the root of this issue. What did the author try to do with it? Did he want to ignore a directory named git/ instead of .git/?

Console output verbosity

Hello,

Is there any way to turn off console verbosity?
Anytime a file refreshes, livereload prints out 5 lines in the console (including newlines).

Refresh: path/to/file

Browser connected.

Browser URL: {"command":"hello","protocols":["http://livereload.com/protocols/official-6","http://livereload.com/protocols/official-7"],"ver":"2.2.1","ext":"Chrome","extver":"2.1.0"}

That's not very helpful and makes the console unreadable if run in parallel with other tasks, such as a watch job.

Is there a CLI option to turn that off?

Add glob file watches

What version are you using? (Don't say latest. Be specific.)

0.6.0

Expected result

I would expect LiveReload to be able to watch glob patterns instead of just a dir and extensions.

Example:

const list = [
	path.join(dir, '**/*.md'),
	path.join(dir, '**/*.text'),
];

const liveReloadServer = liveReload.createServer({
	port: 35729
}).watch(list);

Actual result

I have to combine extensions and dirs to get the right result, which does not work for everything. For example, I want to ignore all **/*.js files, but I want one particular.js file to trigger the reload.

Steps to reproduce issue

Use the code above.

Why is this important?

Flexibility.

Arrays of Extensions Not Accepted as per Documentation

What version are you using? (Don't say latest. Be specific.)

0.6.0

Expected result

The README says

"exts is an array of extensions you want to observe. "

https://github.com/napcs/node-livereload/blame/master/README.md#L156

Example:

const ary = [
    '.md',
    '.text'
];

const liveReloadServer = liveReload.createServer({
	port: 35729,
        exts: ary
}).watch(list);

Actual result

Nothing happens when you pass an array, you have to pass a string.

Example:

const ary = [
    '.md',
    '.text'
];

const liveReloadServer = liveReload.createServer({
	port: 35729,
        exts: ary.join(' ')
}).watch(list);

Steps to reproduce issue

Use the code above.

Why is this important?

Docs are confusing. The JavaScript part of the API could be more JavaScript~y.

'reloadStylesheetImages' function has a bug in Chrome browser

ext/livereload.js:

Reloader.prototype.reloadImages = function(path) {
  var expando, img, selector, styleNames, styleSheet, _i, _j, _k, _l, _len, _len1, _len2, _len3, _ref, _ref1, _ref2, _ref3, _results;
  // ...
  if (this.document.styleSheets) {
    _ref3 = this.document.styleSheets;
    _results = [];
    for (_l = 0, _len3 = _ref3.length; _l < _len3; _l++) {
      styleSheet = _ref3[_l];
      _results.push(this.reloadStylesheetImages(styleSheet, path, expando));
    }
    return _results;
  }
};

Reloader.prototype.reloadStylesheetImages = function(styleSheet, path, expando) {
  var rule, rules, styleNames, _i, _j, _len, _len1;
  try {
    rules = styleSheet != null ? styleSheet.cssRules : void 0;
  } catch (e) {

  }
  if (!rules) {
    console.log('no rules.')
    return;
  }
  // ...
}

In Chrome, the cssRules property is null of styleSheet object, so the function reloadStylesheetImages always be return.

image

Add 'alert' command support

For use as part of a build process, when the build script is watching files and running in background in some console, it would be useful to be able to send an alert message if something goes wrong in the build.

With the build console in the background (personally I have an editor on my first monitor and browser on the other, with no place left for console) the user has no way of knowing the build is failing and therefore why the reload is not happening. An alert fixes that with a very visible notification whenever I make a build-failing error.

I tried to get that into a pull request here: #86 . I'm not very proficient in OSS and Github though, so feel free to correct me in any way.

Windows 8.1: build error MSB6006 (CL.exe exit code 5)

I get a build error during install of livereload on my Windows 8.1 PC:

USERNAME@MYPC C:\
$ npm install -g livereload
npm WARN install Couldn't install optional dependency: Unsupported
C:\nvm\nodejs\livereload -> C:\nvm\nodejs\node_modules\livereload\bin\livereload.js

> [email protected] install C:\nvm\nodejs\node_modules\livereload\node_modules\bufferutil
> node-gyp rebuild


USERNAME@MYPC C:\nvm\nodejs\node_modules\livereload\node_modules\bufferutil
$ if not defined npm_config_node_gyp (node "C:\nvm\nvm-windows\v5.4.0\node_modules\npm\bin\node-gyp-bin\\..\..\node_modules\node-gyp\bin\node-gyp.js" rebuild )  else (node  rebuild )
Die Projekte in dieser Projektmappe werden nacheinander erstellt. Um eine parallele Erstellung zu ermöglichen, müssen Sie den Schalter "/m" hinzufügen.
  TRACKER : Fehler TRK0005: Fehler beim Suchen von "CL.exe". Das System kann die angegebene Datei nicht finden.


C:\Program Files (x86)\MSBuild\Microsoft.Cpp\v4.0\V140\Microsoft.CppCommon.targets(356,5): error MSB6006: "CL.exe" wurde mit dem Code 5 beendet. [C:\nvm\nodejs\node_modules\livereload\node_modules\bufferutil\build\bufferutil.vcxproj]
gyp ERR! build error
gyp ERR! stack Error: `C:\Program Files (x86)\MSBuild\14.0\bin\msbuild.exe` failed with exit code: 1
gyp ERR! stack     at ChildProcess.onExit (C:\nvm\nvm-windows\v5.4.0\node_modules\npm\node_modules\node-gyp\lib\build.js:270:23)
gyp ERR! stack     at emitTwo (events.js:87:13)
gyp ERR! stack     at ChildProcess.emit (events.js:172:7)
gyp ERR! stack     at Process.ChildProcess._handle.onexit (internal/child_process.js:200:12)
gyp ERR! System Windows_NT 6.3.9600
gyp ERR! command "C:\\nvm\\nodejs\\node.exe" "C:\\nvm\\nvm-windows\\v5.4.0\\node_modules\\npm\\node_modules\\node-gyp\\bin\\node-gyp.js" "rebuild"
gyp ERR! cwd C:\nvm\nodejs\node_modules\livereload\node_modules\bufferutil
gyp ERR! node -v v5.4.0
gyp ERR! node-gyp -v v3.0.3
gyp ERR! not ok
npm WARN install:[email protected] [email protected] install: `node-gyp rebuild`
npm WARN install:[email protected] Exit status 1

> [email protected] install C:\nvm\nodejs\node_modules\livereload\node_modules\utf-8-validate
> node-gyp rebuild


USERNAME@MYPC C:\nvm\nodejs\node_modules\livereload\node_modules\utf-8-validate
$ if not defined npm_config_node_gyp (node "C:\nvm\nvm-windows\v5.4.0\node_modules\npm\bin\node-gyp-bin\\..\..\node_modules\node-gyp\bin\node-gyp.js" rebuild )  else (node  rebuild )
Die Projekte in dieser Projektmappe werden nacheinander erstellt. Um eine parallele Erstellung zu ermöglichen, müssen Sie den Schalter "/m" hinzufügen.
  TRACKER : Fehler TRK0005: Fehler beim Suchen von "CL.exe". Das System kann die angegebene Datei nicht finden.


C:\Program Files (x86)\MSBuild\Microsoft.Cpp\v4.0\V140\Microsoft.CppCommon.targets(356,5): error MSB6006: "CL.exe" wurde mit dem Code 5 beendet. [C:\nvm\nodejs\node_modules\livereload\node_modules\utf-8-validate\build\validation.vcxproj]
gyp ERR! build error
gyp ERR! stack Error: `C:\Program Files (x86)\MSBuild\14.0\bin\msbuild.exe` failed with exit code: 1
gyp ERR! stack     at ChildProcess.onExit (C:\nvm\nvm-windows\v5.4.0\node_modules\npm\node_modules\node-gyp\lib\build.js:270:23)
gyp ERR! stack     at emitTwo (events.js:87:13)
gyp ERR! stack     at ChildProcess.emit (events.js:172:7)
gyp ERR! stack     at Process.ChildProcess._handle.onexit (internal/child_process.js:200:12)
gyp ERR! System Windows_NT 6.3.9600
gyp ERR! command "C:\\nvm\\nodejs\\node.exe" "C:\\nvm\\nvm-windows\\v5.4.0\\node_modules\\npm\\node_modules\\node-gyp\\bin\\node-gyp.js" "rebuild"
gyp ERR! cwd C:\nvm\nodejs\node_modules\livereload\node_modules\utf-8-validate
gyp ERR! node -v v5.4.0
gyp ERR! node-gyp -v v3.0.3
gyp ERR! not ok
npm WARN install:[email protected] [email protected] install: `node-gyp rebuild`
npm WARN install:[email protected] Exit status 1
C:\nvm\nodejs
└─┬ [email protected]
  ├─┬ [email protected]
  │ ├─┬ [email protected]
  │ │ ├── [email protected]
  │ │ └─┬ [email protected]
  │ │   ├─┬ [email protected]
  │ │   │ └── [email protected]
  │ │   ├── [email protected]
  │ │   ├─┬ [email protected]
  │ │   │ ├─┬ [email protected]
  │ │   │ │ └─┬ [email protected]
  │ │   │ │   ├── [email protected]
  │ │   │ │   ├── [email protected]
  │ │   │ │   ├── [email protected]
  │ │   │ │   └── [email protected]
  │ │   │ ├── [email protected]
  │ │   │ └── [email protected]
  │ │   ├─┬ [email protected]
  │ │   │ └── [email protected]
  │ │   ├── [email protected]
  │ │   ├── [email protected]
  │ │   ├─┬ [email protected]
  │ │   │ └── [email protected]
  │ │   ├── [email protected]
  │ │   ├─┬ [email protected]
  │ │   │ ├─┬ [email protected]
  │ │   │ │ └── [email protected]
  │ │   │ └── [email protected]
  │ │   ├─┬ [email protected]
  │ │   │ ├── [email protected]
  │ │   │ └── [email protected]
  │ │   └─┬ [email protected]
  │ │     ├── [email protected]
  │ │     └── [email protected]
  │ ├── [email protected]
  │ ├── [email protected]
  │ ├── [email protected]
  │ ├─┬ [email protected]
  │ │ └── [email protected]
  │ ├─┬ [email protected]
  │ │ └── [email protected]
  │ ├── [email protected]
  │ └─┬ [email protected]
  │   ├── [email protected]
  │   ├─┬ [email protected]
  │   │ └─┬ [email protected]
  │   │   ├── [email protected]
  │   │   └── [email protected]
  │   └─┬ [email protected]
  │     ├── [email protected]
  │     ├─┬ [email protected]
  │     │ ├─┬ [email protected]
  │     │ │ ├── [email protected]
  │     │ │ ├── [email protected]
  │     │ │ ├── [email protected]
  │     │ │ └── [email protected]
  │     │ └─┬ [email protected]
  │     │   ├── [email protected]
  │     │   └── [email protected]
  │     ├── [email protected]
  │     ├── [email protected]
  │     ├── [email protected]
  │     ├─┬ [email protected]
  │     │ ├── [email protected]
  │     │ └─┬ [email protected]
  │     │   ├── [email protected]
  │     │   ├── [email protected]
  │     │   ├── [email protected]
  │     │   └── [email protected]
  │     └── [email protected]
  ├── [email protected]
  └─┬ [email protected]
    ├── [email protected]
    └── [email protected]

I can run it

USERNAME@MYPC C:\tmp
$ livereload .\
Starting LiveReload v0.4.1 for C:\tmp on port 35729.

but it does not reload any files in my browser. However, it works if I use the regular GUI-Version (I installed Windows version LiveReload 0.9.2 Alpha) instead. Nevertheless, I would prefer to use livereload from the commandline.

nasty regex bug triggering unwanted exclusions

Hello,

I just wanted to (at long last !) install livereload in my project. However your nice little server didn't detect my file changes !

After debugging, it appears that because my workspace is in a path like that : /work/git/my_repo (yes, I put my repos in a git dir ;) that incorrectly triggers the .git exclusion :

watch event !
/work/git/tests/html_tests/toto.html
excluded by \.git/

I tested with an extra escaping in lib/livereload.js : defaultExclusions = ['\\.git/', ... and it does the trick : correctly ignores /.git/ but doesn't exclude /git/.

I'm not confident enough in coffeescript to send you a PR. Can you fix it ?

Thanks. Otherwise it works well !

Server crashes Error: read ECONNRESET

Everytime I save a file when threre is a browser connected, the server crashes a few seconds after...

...
Refresh: /tmp/xxx/presentation.html


events.js:72
        throw er; // Unhandled 'error' event
              ^
Error: read ECONNRESET
    at errnoException (net.js:884:11)
    at TCP.onread (net.js:539:19)

Server not serving pages. No error message shown.

Hi,
I'm trying to use this package, but whenever I try to use it, the browser will just keep stuck on loading the page.
I tried with the basic example:
1- installing livereload locally
2- creating a node server.js file
3- writing down the lines you wrote to create the basic server
4- adding in the public folder with index.html and the script you wrote on the welcome page.
5- going to http://localhost:35729 or http://localhost:35729/index.html

I've also tried using it globally with livereload public/ but so far it didn't work.

Thank you for your work.

exclusions ignored, CPU Usage constantly 100%

On OS X with node 4.x, 6.x, and the livereload 0.4.0 and 0.5.0

I was serving directly from a folder with a large node_modules inside and the CPU spiked to 100% and would take full seconds to respond to requests.

I tried adding { exclusions: [ 'node_modules', '.git' ] } and it still went up to 100%.

I try a different folder with only a few files and it's not a problem.

this.reloader NPE on IE8

I know this won't be a huge priority to fix, but at least on IE8 (maybe later ones as well) including the client-side livereload.js triggers the following error on line 961:

'this.reloader' is null or not an object

Might just add a check before accessing that property, so old & buggy browser will fail quietly (e.g. just no livereload) instead of making noise.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.