我发现了如何使用 os.networkInterfaces() 轻松获取当前 LAN ip,如 nodejs 文档http://nodejs.org/api/os.html#os_os_networkinterfaces中所述
因此,如果需要为 intern.js 的静态 proxyUrl 配置标志自动动态获取 localLan ip,我们只需在您的 Gruntfile 的定义中添加相应的代码,因为 Grunt 本身正在 nodejs 环境中执行:
/* jshint node: true*/
"use strict";
module.exports = function (grunt) {
require("time-grunt")(grunt);
var os = require('os');
var interfaces = os.networkInterfaces(),
localLanIp = null,
setLocalLanIp = function (deviceDetails) {
if (deviceDetails.family === 'IPv4' && !deviceDetails.internal) {
localLanIp = deviceDetails.address;
}
return localLanIp !== null;
};
for (var device in interfaces) {
//just check devices containing LAN or eth
if (device.indexOf("LAN") > -1 || device.indexOf("eth") > -1) {
//as we can'T break a forEach on arrays we use some and break on return true.
interfaces[device].some(setLocalLanIp);
//break outer for as loaclIp is found.
if (localLanIp !== null) {
break;
}
}
}
//if no ip found default to localhost anyway.
if (localLanIp === null) {
localLanIp = "localhost";
}
grunt.initConfig({
intern: {
remote: {
options: {
runType: "runner",
config: "tests/intern.js",
reporters: [ "console" ],
suites: [ "tests/module" ],
proxyPort: 9000,
proxyUrl: 'http://' + localLanIp + ':' + 9000
}
}
}
});
grunt.loadNpmTasks("intern");
grunt.registerTask("default", ["intern"]);
};
在我看来,默认为本地 LAN ip 是一个好主意,但如果您不能依赖 localhost 或 0.0.0.0 地址但不想手动编辑任何配置(或不能由于任何原因)。