# bare-signals

<mark style="{ backgroundColor: '#7dde9a', padding: '2px 8px', borderRadius: '4px', fontSize: '0.85em', fontWeight: 500 }">
  stable
</mark>

[`bare-signals`](https://github.com/holepunchto/bare-signals) — Native signal handling for JavaScript. It is a native addon and requires Bare `>=1.7.0`.

```sh
npm i bare-signals
```

## Usage [#usage]

```js
const Signal = require('bare-signals')

const sigint = new Signal('SIGINT')

sigint.on('signal', () => console.log('SIGINT caught')).start()
```

## API [#api]

### Signal [#signal]

#### `new Signal(signum: number | string)` [#new-signalsignum-number--string]

Create a `Signal` for `signum`, given as a signal number or name such as `'SIGINT'`. Throws if `signum` is a string that names an unknown signal.

**Parameters**

| Parameter | Type                 | Default | Description                                                                  |
| --------- | -------------------- | ------- | ---------------------------------------------------------------------------- |
| `signum`  | `number` \| `string` | —       | The signal to handle, given as a signal number or a name such as `'SIGINT'`. |

**Throws**

* `UNKNOWN_SIGNAL` — `signum` is a string that does not name a known signal.

#### `close(): Promise<void>` [#close-promisevoid]

Close the signal, releasing its underlying handle. Returns a promise that resolves once the `close` event has fired.

#### `Signal.ref(): this` [#signalref-this]

Ref the signal, keeping the event loop alive while it is active.

#### `Signal.constants: Record<string, number>` [#signalconstants-recordstring-number]

The map of known signal names to signal numbers.

#### `start(): this` [#start-this]

Start listening for the signal, emitting `signal` when it is received. Throws if the signal has been closed.

**Throws**

* `SIGNAL_CLOSED` — the signal has been closed.

#### `stop(): this` [#stop-this]

Stop listening for the signal.

#### `Signal.unref(): this` [#signalunref-this]

Unref the signal, allowing the event loop to exit even while it is active.

### SignalEmitter [#signalemitter]

#### `SignalEmitter.ref(): this` [#signalemitterref-this]

Ref all currently tracked signals, keeping the event loop alive.

#### `SignalEmitter.unref(): this` [#signalemitterunref-this]

Unref all currently tracked signals, allowing the event loop to exit.

### Classes [#classes]

#### `SignalError` [#signalerror]

```ts
class SignalError {
  code: string
}
```

An error thrown by `bare-signals`, such as for an unknown signal name or an operation on a closed signal.

## See also [#see-also]

* Builds on `bare-events`.
* [Bare modules](/bare/reference/bare/modules) — the full `bare-*` catalog.
* [Bare runtime API](/bare/reference/bare/runtime) — the runtime these modules extend.