Skip to content

Commit

Permalink
feat: add http server and how to use doc
Browse files Browse the repository at this point in the history
  • Loading branch information
hubcarl committed Sep 28, 2018
1 parent 1bde147 commit eae9f63
Show file tree
Hide file tree
Showing 5 changed files with 185 additions and 56 deletions.
79 changes: 78 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -20,10 +20,87 @@
[download-image]: https://img.shields.io/npm/dm/node-tool-utils.svg?style=flat-square
[download-url]: https://npmjs.org/package/node-tool-utils

Node Tool Utils
Node Cross-Platform Tool Library

## Featues

```bash
npm install node-tool-utils --save
```

## Usage

```js
const tool = require('node-tool-utils');
```

### Get Local IP Address

```js
const ip = tool.getIP();
```

### Get Local Host

```js
const host = tool.getHost(7001);
// http://100.10.196.1:7001
```

### Kill the occupied port

```js
tool.kill(7001);
tool.kill([7001,7002]);
```

### Check port is available

```js
// return true or false
const isUsed = tool.checkPortUsed(7001);
```

### Get an available port

When 7001 is occupied, it will automatically detect whether 7002 is occupied. If it is not occupied, it will return. Otherwise, it will continue to increment detection. The default check is 10 times.

```js
const port = tool.getPort(7001);
```

### Delete File

```js
const dir = path.join(__dirname, 'dist/index.html');
tool.deleteFile(dir);
```

### Delete Dir

```js
const dir = path.join(__dirname, 'dist');
tool.rm(dir);
```

### Open Browser Or Window

Open the Window or Finder or Browser of the specified path

```js
tool.open('.'); // open Window or Finder
tool.openBrowser(); // open Browser
```

### Start Web Http Server

Default check HTML file as homepage

``js
const dist = path.join(__dirname, 'dist');
tool.httpserver({ port: 8088, dist },() => {});
```
## License
[MIT](LICENSE)
5 changes: 5 additions & 0 deletions index.js
Original file line number Diff line number Diff line change
@@ -1,2 +1,7 @@
'use strict';
module.exports = require('./lib/tool');
exports.chalk = require('chalk');
exports.shell = require('shelljs');
exports.glob = require('glob');
exports.httpserver = require('node-http-server');
exports.opn = require('opn');
146 changes: 95 additions & 51 deletions lib/tool.js
Original file line number Diff line number Diff line change
@@ -1,25 +1,102 @@
'use strict';
const path = require('path');
const os = require('os');
const fs = require('fs');
const path = require('path');
const chalk = require('chalk');
const shell = require('shelljs');
const opn = require('opn');
const killer = require('cross-port-killer');
const httpserver = require('node-http-server');
const glob = require('glob');


exports.resolve = (filename, baseDir) => {
baseDir = baseDir || process.cwd();
if (filename) {
return path.isAbsolute(filename) ? filename : path.resolve(baseDir, filename);
}
return baseDir;
};

exports.getIp = position => {
const interfaces = os.networkInterfaces();
const ips = [];

if (interfaces.en0) {
for (let i = 0; i < interfaces.en0.length; i++) {
if (interfaces.en0[i].family === 'IPv4') {
ips.push(interfaces.en0[i].address);
}
}
}
if (interfaces.en1) {
for (let i = 0; i < interfaces.en1.length; i++) {
if (interfaces.en1[i].family === 'IPv4') {
ips.push(interfaces.en1[i].address);
}
}
}
if (position > 0 && position <= ips.length) {
return ips[position - 1];
} else if (ips.length) {
return ips[0];
}
return '127.0.0.1';
};

exports.getHost = port => {
const ip = exports.getIp();
if (port) {
return `http://${ip}:${port}`;
}
return `http://${ip}`;
};

exports.httpServer = (cfg, callback) => {
const port = cfg.port || 8080;
const root = exports.resolve(cfg.dist);
let index = cfg.index;
if (!index) {
const files = glob.sync('*.html', { cwd: root, root });
if (files.length > 0) {
index = files[0];
}
}
const options = {
port,
root,
server: {
index
}
};
httpserver.deploy(options, server => {
const url = `http://127.0.0.1:${server.config.port}`;
const host = exports.getHost(server.config.port);
console.log(chalk.green(`Http server ${chalk.yellow(url)} or ${chalk.yellow(host)} is serve ${chalk.blue(root)}\r\n`));
callback && callback(server);
});
};

exports.exec = cmd => {
return shell.exec(cmd);
};

exports.rm = filepath => {
const dirs = Array.isArray(filepath) ? filepath : [filepath];
dirs.forEach(dir => {
/* istanbul ignore next */
if (os.platform() === 'win32') {
exports.deleteFile(dir);
console.log(`remove [ ${dir} ] success`);
} else {
const result = shell.exec(`rm -rf ${dir}`);
if (result.code === 0) {
if (fs.existsSync(dir)) {
/* istanbul ignore next */
if (os.platform() === 'win32') {
exports.deleteFile(dir);
console.log(`remove [ ${dir} ] success`);
} else {
/* istanbul ignore next */
exports.deleteFile(dir);
const result = shell.exec(`rm -rf ${dir}`);
if (result.code === 0) {
console.log(`remove [ ${dir} ] success`);
} else {
/* istanbul ignore next */
exports.deleteFile(dir);
}
}
}
});
Expand All @@ -42,7 +119,7 @@ exports.deleteFile = filepath => {
fs.unlinkSync(filepath);
}
}
}
};

/* istanbul ignore next */
exports.open = filepath => {
Expand All @@ -63,12 +140,11 @@ exports.open = filepath => {
}
};

exports.openBrowser = (url, port) => {
if (!url && port) {
const ip = utils.getIp();
url = `http://${ip}:${port}`;
exports.openBrowser = (port, url) => {
if (!url) {
url = exports.getHost(port);
}
open(url);
opn(url);
};

exports.checkPortUsed = port => {
Expand Down Expand Up @@ -98,7 +174,7 @@ exports.checkPortUsed = port => {
exports.getPort = (port, count = 10) => {
let newPort = port;
let checkPort = port;
while(checkPort < port + count) {
while (checkPort < port + count) {
const isUsed = exports.checkPortUsed(checkPort);
if (!isUsed) {
newPort = checkPort;
Expand All @@ -110,10 +186,9 @@ exports.getPort = (port, count = 10) => {
};

/* istanbul ignore next */
exports.kill = function (port) {
exports.kill = function(port) {
if (port) {
port = String(port);
const ports = port.split(',');
const ports = Array.isArray(port) ? port : String(port).split(',');
ports.forEach(p => {
killer.kill(p).then(() => {
console.log(`kill port ${p} success`);
Expand All @@ -122,35 +197,4 @@ exports.kill = function (port) {
});
});
}
};

exports.getIp = position => {
const interfaces = os.networkInterfaces();
const ips = [];

if (interfaces.en0) {
for (let i = 0; i < interfaces.en0.length; i++) {
if (interfaces.en0[i].family === 'IPv4') {
ips.push(interfaces.en0[i].address);
}
}
}
if (interfaces.en1) {
for (let i = 0; i < interfaces.en1.length; i++) {
if (interfaces.en1[i].family === 'IPv4') {
ips.push(interfaces.en1[i].address);
}
}
}
if (position > 0 && position <= ips.length) {
return ips[position - 1];
} else if (ips.length) {
return ips[0];
}
return '127.0.0.1';
};

exports.getHost = port => {
const ip = exports.getIp();
return `http://${ip}:${port}`;
};
9 changes: 6 additions & 3 deletions package.json
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
{
"name": "node-tool-utils",
"version": "0.1.0",
"description": "node normal tool and utils",
"version": "1.1.0",
"description": "node cross-platform tool library",
"keywords": [
"npm",
"npm package",
Expand All @@ -13,9 +13,12 @@
"changelog"
],
"dependencies": {
"chalk": "^2.0.1",
"cross-port-killer": "^1.0.1",
"opn": "^5.4.0",
"shelljs": "^0.8.2"
"shelljs": "^0.8.2",
"node-glob": "^1.2.0",
"node-http-server": "^8.1.2"
},
"devDependencies": {
"chai": "^4.1.1",
Expand Down
2 changes: 1 addition & 1 deletion test/index.js
Original file line number Diff line number Diff line change
@@ -1,3 +1,3 @@
const tool = require('../lib/tool');
const port = tool.getPort(9000);
tool.kill(7001);
console.log(port);

0 comments on commit eae9f63

Please sign in to comment.