nodejs获取 本地ip地址

vue本地项目,想要在手机端访问的时候,需要在vue.config.js的devServe中修改 host的值

host: "localhost"  ==>  host: "**.**.**.**"

但每次启动前都要手动查询ipconfig/ifconfig,比较麻烦。

所以,用nodejs的‘os’来自动获取本地ip

 1 'use strict'
 2 const os = require('os')
 3 
 4 /**
 5  * 获取当前机器的ip地址
 6  */
 7 function getIpAddress() {
 8   var interfaces=os.networkInterfaces()
 9 
10   for (var dev in interfaces) {
11     let iface = interfaces[dev]
12 
13     for (let i = 0; i < iface.length; i++) {
14       let {family, address, internal} = iface[i]
15 
16       if (family === 'IPv4' && address !== '127.0.0.1' && !internal) {
17         return address
18       }
19     }
20   }
21 }
22 
23 const ipAddress = getIpAddress()
24 console.log(ipAddress)
25 
26 module.exports = {
27   ipAddress
28 }