Skip to content

Commit

Permalink
Add logging parameter to find
Browse files Browse the repository at this point in the history
On some Linux systems netstat will output a warning if not run as root.
This API gives API users more control over showing this warning:

```javascript
const processes = await find('port', 80, { logLevel: 'error' });
```

This change is backwards compatible:

```javascript
// Equivalent
await find('name', 'nginx', true),
await find('name', 'nginx', { strict: true }),

// Equivalent
await find('name', 'nginx'),
await find('name', 'nginx', false),
await find('name', 'nginx', { strict: false}),
```

fix yibn2008#59
  • Loading branch information
blakef committed May 18, 2022
1 parent f6adc9b commit b57f9c8
Show file tree
Hide file tree
Showing 8 changed files with 74 additions and 21 deletions.
16 changes: 14 additions & 2 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -71,14 +71,16 @@ find('pid', 12345)
## Synopsis

```
Promise<Array> find(type, value, [strict])
Promise<Array> find(type, value, [options])
```

**Arguments**

- `type` the type of find, support: *port|pid|name*
- `value` the value of type, can be RegExp if type is *name*
- `strict` the optional strict mode is for checking *port*, *pid*, or *name* exactly matches the given one. (on Windows, `.exe` can be omitted)
- `options` this can either be the *object* described below or *boolean* to just set strict mode
- `options.strict` the optional strict mode is for checking *port*, *pid*, or *name* exactly matches the given one. (on Windows, `.exe` can be omitted)
- `options.logLevel` set the logging level to [`trace|debug|info|warn|error`](https://github.com/pimterry/loglevel#documentation). In practice this lets you silence a netstat warning on Linux.

**Return**

Expand Down Expand Up @@ -139,6 +141,16 @@ find('name', 'nginx', true)
});
```

Find all nginx processes on Linux without logging a warning when run as a user who isn't root.

```javascript
const find = require('find-process');

find('name', 'nginx', {strict: true, logLevel: 'error'})
.then(function (list) {
console.log('there are %s nginx process(es)', list.length);
});
```
## Contributing

We're welcome to receive Pull Request of bugfix or new feature, but please check the list before sending PR:
Expand Down
4 changes: 2 additions & 2 deletions bin/find-process.js
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@

const program = require('commander')
const chalk = require('chalk')
const debug = require('debug')('find-process')
const log = require('loglevel').getLogger('find-process')
const find = require('..')
const pkg = require('../package.json')

Expand Down Expand Up @@ -54,7 +54,7 @@ if (opts.port) {
type = opts.type
}

debug('find process by: type = %s, keyword = "%s"', type, keyword)
log.debug('find process by: type = %s, keyword = "%s"', type, keyword)

find(type, keyword)
.then(list => {
Expand Down
30 changes: 28 additions & 2 deletions index.d.ts
Original file line number Diff line number Diff line change
@@ -1,9 +1,35 @@
declare function find(type: "name" | "pid" | "port", value: string | number | RegExp, strict?: boolean): Promise<{
// https://github.com/pimterry/loglevel/blob/f5a642299bf77a81118d68766a168c9568ecd21b/index.d.ts#L14-L38
interface LogLevel {
TRACE: 0;
DEBUG: 1;
INFO: 2;
WARN: 3;
ERROR: 4;
SILENT: 5;
}

type LogLevelNumbers = LogLevel[keyof LogLevel];

type LogLevelDesc = LogLevelNumbers
| 'trace'
| 'debug'
| 'info'
| 'warn'
| 'error'
| 'silent'
| keyof LogLevel;

declare type Options = {
strict?: boolean;
logLevel?: LogLevelDesc;
}

declare function find(type: "name" | "pid" | "port", value: string | number | RegExp, strict?: boolean | Option): Promise<{
pid: number;
ppid?: number;
uid?: number;
gid?: number;
name: string;
cmd: string;
}[]>
export = find;
export = find;
29 changes: 19 additions & 10 deletions lib/find.js
Original file line number Diff line number Diff line change
Expand Up @@ -9,27 +9,28 @@

const findPid = require('./find_pid')
const findProcess = require('./find_process')
const log = require('./logger')

const findBy = {
port (port, strict) {
return findPid(port, strict)
port (port, config) {
return findPid(port)
.then(pid => {
return findBy.pid(pid, strict)
return findBy.pid(pid, config)
}, () => {
// return empty array when pid not found
return []
})
},
pid (pid, strict) {
pid (pid, config) {
return findProcess({
pid: pid,
strict
config
})
},
name (name, strict) {
name (name, config) {
return findProcess({
name: name,
strict
config
})
}
}
Expand All @@ -48,11 +49,19 @@ const findBy = {
*
* If no process found, resolve process with empty array (only reject when error occured)
*
* @param {String} by condition: port/pid/name ...
* @param {String} by condition: port/pid/name ...
* @param {Mixed} condition value
* @param {Boolean|Option}
* @return {Promise}
*/
function find (by, value, strict) {
function find (by, value, options) {
const config = Object.assign({
logLevel: 'warn',
strict: typeof options === 'boolean' ? options : false
}, options)

log.setLevel(config.logLevel)

return new Promise((resolve, reject) => {
if (!(by in findBy)) {
reject(new Error(`do not support find by "${by}"`))
Expand All @@ -63,7 +72,7 @@ function find (by, value, strict) {
} else if (by === 'port' && !isNumber) {
reject(new Error('port must be a number'))
} else {
findBy[by](value, strict).then(resolve, reject)
findBy[by](value, config).then(resolve, reject)
}
}
})
Expand Down
3 changes: 2 additions & 1 deletion lib/find_pid.js
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@
const os = require('os')
const fs = require('fs')
const utils = require('./utils')
const log = require('./logger')

const ensureDir = (path) => new Promise((resolve, reject) => {
if (fs.existsSync(path)) {
Expand Down Expand Up @@ -71,7 +72,7 @@ const finders = {
const warn = stderr.toString().trim()
if (warn) {
// netstat -p ouputs warning if user is no-root
console.warn(warn)
log.warn(warn)
}

// replace header
Expand Down
6 changes: 3 additions & 3 deletions lib/find_process.js
Original file line number Diff line number Diff line change
Expand Up @@ -106,7 +106,7 @@ const finders = {
}
})

if (cond.strict && cond.name) {
if (cond.config.strict && cond.name) {
list = list.filter(item => item.name === cond.name)
}

Expand Down Expand Up @@ -137,7 +137,7 @@ const finders = {
return row.ProcessId === String(cond.pid)
} else if (cond.name) {
const rowName = row.Name || '' // fix #40
if (cond.strict) {
if (cond.config.strict) {
return rowName === cond.name || (rowName.endsWith('.exe') && rowName.slice(0, -4) === cond.name)
} else {
// fix #9
Expand Down Expand Up @@ -206,7 +206,7 @@ const finders = {
}
})

if (cond.strict && cond.name) {
if (cond.config.strict && cond.name) {
list = list.filter(item => item.name === cond.name)
}

Expand Down
5 changes: 5 additions & 0 deletions lib/logger.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
'use strict'

const log = require('loglevel')

module.exports = log
2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -53,7 +53,7 @@
"dependencies": {
"chalk": "^4.0.0",
"commander": "^5.1.0",
"debug": "^4.1.1"
"loglevel": "^1.8.0"
},
"devDependencies": {
"mocha": "^7.2.0",
Expand Down

0 comments on commit b57f9c8

Please sign in to comment.