如何将实时重新加载添加到我的 nodejs 服务器

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/45622125/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-02 18:25:39  来源:igfitidea点击:

How can I add live-reload to my nodejs server

node.jsreactjsexpresslivereload

提问by Rebai Ahmed

This is how can i run my server nodejs. I need to live reload my server when i make changes to the code in the front-end dev

这是我如何运行我的服务器 nodejs。当我对前端开发中的代码进行更改时,我需要实时重新加载我的服务器

"start": "node server.js"

回答by Mark Essel

first:

第一的:

npm install -g nodemon

nextadd a script line to your package.json

接下来在你的 package.json 中添加一个脚本行

"live": "nodemon server.js" 

now when you npm live it'll live reload

现在当你 npm live 时,它​​会重新加载

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

有关更多详细信息,请参阅https://github.com/remy/nodemon

updateif live page reload is also needed

如果还需要重新加载实时页面,请更新

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

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

有关更多详细信息,请参阅https://github.com/napcs/node-livereload

回答by Alonad

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.

重启服务器是一回事,刷新浏览器是另一回事。对于服务器观看,我使用 nodemon。Nodemon 可以看到任何类型的文件何时发生更改。但是 nodemon 无法刷新浏览器页面。为此,我使用浏览器同步。

I use both in gulp.

我在 gulp 中同时使用两者。

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

因此,依赖 package.json 使其工作:

"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.

在服务器文件中(我的服务器在 ./bin/www 中,你的可以在 server.js、app.js 或其他地方),express server 监听端口 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

接下来是在 gulp 中运行 nodemon 和浏览器同步。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.

在终端中运行 gulp 时,它将开始监视服务器并在任何文件发生变化时刷新浏览器。

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.

尽管我们在 express 服务器中指定了端口 3001,但我们的应用程序将在端口 3002 上工作,正如我们在浏览器同步中所写的那样。3001 将用作代理。

回答by Murat ?imen

npm install browser-refresh -g

and add your main js

并添加您的主要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

并在终端而不是节点 server.js 上启动您的服务器

browser-refresh server.js

回答by pawel

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)

livereload.js(所以这就是你的server.js,当然只使用livereload相关的部分,不需要更换你的开发服务器)

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 :35729and a static file server on :3033.

它实际上在 localhost 上启动了两个服务器:livereload 服务器侦听:35729和静态文件服务器在:3033.

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

Livereload 观察dist包含编译文件(js、css、html)的目录。您需要将此代码段添加到应该重新加载的每个 HTML 页面:

<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 :)

如果您不转译/编译/预处理您的 js/css/html 代码(即您直接编辑提供的文件),则观察源目录并完成。否则你需要一个任务来观察源目录的变化并编译到 livereload 观察到的 dist 目录:)

Relevant parts of my package.json:

我的 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 watchbuilds the project and starts the livereload + static file servers. (the build:*tasks omitted for brevity).

$ npm run watch构建项目并启动 livereload + 静态文件服务器。(build:*为简洁起见省略了任务)。

回答by Kayvan Mazaheri

You can use nodemon.
It will watch your project's files and restarts the server when you change them.

您可以使用nodemon
它将监视您的项目文件并在您更改它们时重新启动服务器。

You can install it globally:

您可以全局安装它:

npm install -g nodemon

the run it on your projects directory

在您的项目目录上运行它

cd ./my-project
nodemon


You can also add it to your project's dev dependencies and use it from an npm script:

您还可以将其添加到项目的开发依赖项中,并从 npm 脚本中使用它:

npm install --save-dev nodemon

Then add a simple script to your package.json:

然后将一个简单的脚本添加到您的package.json

"scripts": {
    "start": "node server.js",
    "dev": "nodemon"
}

then you can simply run the following command:

那么你可以简单地运行以下命令:

npm run dev

回答by themefield

If gruntis used, there is a npm package grunt-contrib-watchfor live reloading.

如果grunt使用,则有一个grunt-contrib-watch用于实时重新加载的 npm 包。

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

查看另一个称为grunt-express-server可以协同工作的工具。

回答by pspi

You can livereload both front and backend changes to the browser with 'livereload', 'connect-livereload', and 'nodemon' packages. This way you don't need Gulp. Here's how the packages team up:

您可以使用“livereload”、“connect-livereload”和“nodemon”包将前端和后端更改实时重新加载到浏览器。这样你就不需要 Gulp。以下是这些包的组合方式:

  • livereloadopens a high port and notifies the browser of changed public files
  • connect-livereloadmonkey patches every served HTML page with a snippet that connects to this high port
  • nodemonrestarts server on changed backend files
  • livereload打开一个高端口并通知浏览器更改的公共文件
  • connect-livereload猴子使用连接到此高端口的代码段修补每个提供的 HTML 页面
  • nodemon在更改的后端文件上重新启动服务器

Set up livereload in Express

在 Express 中设置 livereload

Set up Express to both start livereload server watching the public directory and ping the browser during nodemon-induced restart:

将 Express 设置为启动 livereload 服务器以监视公共目录并在nodemon诱导重启期间 ping 浏览器:

const livereload = require("livereload");
const connectLivereload = require("connect-livereload");

// open livereload high port and start to watch public directory for changes
const liveReloadServer = livereload.createServer();
liveReloadServer.watch(path.join(__dirname, 'public'));

// ping browser on Express boot, once browser has reconnected and handshaken
liveReloadServer.server.once("connection", () => {
  setTimeout(() => {
    liveReloadServer.refresh("/");
  }, 100);
});

const app = express();

// monkey patch every served HTML so they know of changes
app.use(connectLivereload());

Start Express with nodemon

使用 nodemon 启动 Express

Start the server with nodemon, for example, with a dedicated watch script npm run watch.

使用 nodemon 启动服务器,例如,使用专用的 watch script npm run watch

The key point here is to ignore the public directory that's already being watched by livereload. You can also configure files with non-default extensions, like pug and mustache, to be watched.

这里的关键点是忽略已经被 livereload 监视的公共目录。您还可以配置具有非默认扩展名的文件,例如 pug 和 mustache,以进行监视。

"scripts": {
  "start": "node ./bin/www",
  "watch": "nodemon --ext js,pug --ignore public"
},

You can read a longer explanation in "Refresh front and backend changes to browser with Express, LiveReload and Nodemon."

您可以在“使用 Express、LiveReload 和 Nodemon 刷新浏览器的前端和后端更改”中阅读更长的解释

回答by therj

Use the npm package called livereload.

使用名为livereload的 npm 包。

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

将它与nodemon结合使用,这样客户端和服务器端都可以完美地工作。

npm install livereload nodemon --save

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

--保存开发。我知道我知道!

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

添加浏览器扩展。适用于 Safari、Firefox 和 Google Chrome。把它们弄到这里

Make sure to have this scripts inside package.json.

确保在里面有这个脚本package.json

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

}

}

server.jsis my entry point.

server.js是我的切入点。

Inside the server.jsadd the following:

在里面server.js添加以下内容:

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

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

server.js是我想要 livereload 观看的文件。您也可以添加任何目录而不是文件。

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

In terminal: npm start

在终端: npm start

Click on the extension icon in the browser to connect.

单击浏览器中的扩展图标进行连接。

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

您也可以在不同的终端中分别使用 livereload 和 nodemon。

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

npm start

npm start

npm livereload

npm livereload

npm livereload -p PORT_NUMBERif default is port is already used.

npm livereload -p PORT_NUMBER如果默认端口已被使用。

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.

更新:有时它不能保存一次。再次按 Ctrl+S 重新加载并进行更改。我不知道这是浏览器缓存问题还是包问题。