Node.js自动重启工具 nodemon

为什么要使用

在编写调试Node.js项目,修改代码后,需要频繁的手动close掉,然后再重新启动,非常繁琐。现在,我们可以使用nodemon这个工具,它的作用是监听代码文件的变动,当代码改变之后,自动重启。

如何使用

nodemon

下载

npm install -g  nodemon

-g 代表全局安装,代表所有项目无论有没安装 nodemon,都可以直接在命令行上运行,因此我们不会在项目里的 node_modules 看到 nodemon。

使用

编写代码 app.js

var express = require("express")

var app = express()

app.get('/',function(req,res) {
    res.send("hello world")
})

app.listen(3000,function(){
    console.log('server is running')
})

这里使用了express框架。

传统的方法,我们使用node app.js命令,程序将启动。其实,我们刚才下载的nodemon工具也可以用来启动。

nodemon app.js

我们访问3000端口,可以看到hellloworld。

我们现在尝试修改一下代码:

app.get('/',function(req,res) {
    res.send("hello express")
})

保存之后,我们可以看到命令行中,输出了以下内容:

[nodemon] restarting due to changes...
[nodemon] starting `node app.js`

我们只需要刷新浏览器,就可以看到改动后的内容。

实际上,我们可以看到,nodemon其实也是在调用node命令。


转载于:刘昊2018 https://www.jianshu.com/p/3b3b8bf9c4e9

发布了48 篇原创文章 · 获赞 346 · 访问量 16万+

猜你喜欢

转载自blog.csdn.net/weixin_44253336/article/details/104204288