### Installation Source: https://context7.com/jace254/node-routeros-v2/llms.txt Install the node-routeros package using npm. ```APIDOC ## Installation Install the package via npm. ```bash npm install node-routeros --save ``` ``` -------------------------------- ### Complete CRUD Example for Firewall Rules Source: https://context7.com/jace254/node-routeros-v2/llms.txt Demonstrates create, read, update, and delete operations on RouterOS firewall filter rules using async/await. Ensure the RouterOSAPI is connected before executing operations. ```typescript import { RouterOSAPI } from 'node-routeros'; const conn = new RouterOSAPI({ host: '192.168.88.1', user: 'admin', password: 'secret' }); async function manageFirewallRules() { try { await conn.connect(); console.log('Connected to router'); // CREATE: Add a new firewall filter rule const addResult = await conn.write('/ip/firewall/filter/add', [ '=chain=input', '=protocol=tcp', '=dst-port=22', '=action=accept', '=comment=Allow SSH' ]); const ruleId = addResult[0].ret; console.log('Created rule with ID:', ruleId); // READ: Get all input chain rules const rules = await conn.write('/ip/firewall/filter/print', [ '?chain=input' ]); console.log('Input chain rules:', rules.length); // UPDATE: Modify the rule comment await conn.write('/ip/firewall/filter/set', [ '=.id=' + ruleId, '=comment=SSH Access - Updated' ]); console.log('Rule updated'); // READ: Verify the update const updatedRule = await conn.write('/ip/firewall/filter/print', [ '?.id=' + ruleId ]); console.log('Updated comment:', updatedRule[0].comment); // DELETE: Remove the rule await conn.write('/ip/firewall/filter/remove', [ '=.id=' + ruleId ]); console.log('Rule deleted'); await conn.close(); console.log('Disconnected'); } catch (err) { console.error('Error:', err.message); conn.close(); } } manageFirewallRules(); ``` -------------------------------- ### Install node-routeros Source: https://github.com/jace254/node-routeros-v2/blob/development/README.md Install the node-routeros package using npm. ```bash npm install node-routeros --save ``` -------------------------------- ### Start Continuous Data Stream with stream() Source: https://context7.com/jace254/node-routeros-v2/llms.txt Use stream() to create a continuous data stream for commands that return real-time data. The callback receives error and packet parameters. This example streams network traffic data from torch. ```typescript import { RouterOSAPI } from 'node-routeros'; const conn = new RouterOSAPI({ host: '192.168.88.1', user: 'admin', password: '' }); conn.connect().then(() => { let packetCount = 0; // Start streaming network traffic data from torch const torchStream = conn.stream( ['/tool/torch', '=interface=ether1', '=duration=60'], (err, packet, stream) => { if (err) { console.error('Stream error:', err.message); return; } console.log('Traffic packet:', packet); // packet = { 'tx': '1234', 'rx': '5678', 'tx-packets': '10', ... } packetCount++; // Pause after every 5 packets if (packetCount % 5 === 0) { stream.pause().then(() => { console.log('Stream paused'); // Resume after 3 seconds setTimeout(() => { stream.resume().then(() => { console.log('Stream resumed'); }); }, 3000); }); } // Stop after 30 packets if (packetCount >= 30) { stream.stop().then(() => { console.log('Stream stopped completely'); conn.close(); }); } } ); }); ``` -------------------------------- ### Execute RouterOS Commands Source: https://context7.com/jace254/node-routeros-v2/llms.txt Send commands to the RouterOS device and process the response. This example demonstrates adding an IP address, querying addresses, and removing an address using its ID. Ensure the connection is established before writing commands. ```typescript import { RouterOSAPI } from 'node-routeros'; const conn = new RouterOSAPI({ host: '192.168.88.1', user: 'admin', password: '' }); conn.connect().then(() => { // Add an IP address to an interface conn.write('/ip/address/add', [ '=interface=ether2', '=address=192.168.90.1/24' ]) .then((data) => { console.log('Address added, ID:', data[0].ret); // data = [{ ret: '*1' }] // Query addresses with a filter return conn.write('/ip/address/print', [ '?interface=ether2' ]); }) .then((addresses) => { console.log('Addresses found:', addresses); // addresses = [{ '.id': '*1', address: '192.168.90.1/24', interface: 'ether2', ... }] // Remove the address using its ID return conn.write('/ip/address/remove', [ '=.id=' + addresses[0]['.id'] ]); }) .then(() => { console.log('Address removed successfully'); conn.close(); }) .catch((err) => { console.error('Command error:', err.message); }); }); ``` -------------------------------- ### Handle RouterOS Connection Events Source: https://context7.com/jace254/node-routeros-v2/llms.txt The `RouterOSAPI` class emits 'error', 'close', and 'timeout' events. This example demonstrates listening for errors and attempting to reconnect after a delay. ```typescript import { RouterOSAPI } from 'node-routeros'; const conn = new RouterOSAPI({ host: '192.168.88.1', user: 'admin', password: '' }); // Handle connection errors conn.on('error', (err) => { console.error('Connection error:', err.message); // Attempt reconnection after delay setTimeout(() => { conn.connect().catch(console.error); }, 5000); }); // Handle connection close conn.on('close', () => { console.log('Connection closed'); }); conn.connect() .then(() => { console.log('Connected, monitoring connection state...'); }) .catch((err) => { console.error('Initial connection failed:', err.message); }); ``` -------------------------------- ### Write Command and Handle Events with writeStream() Source: https://context7.com/jace254/node-routeros-v2/llms.txt Use writeStream() to write a command and receive data through event listeners ('data', 'done', 'trap', 'close'). This provides more flexibility for complex streaming scenarios. This example monitors interface traffic. ```typescript import { RouterOSAPI } from 'node-routeros'; const conn = new RouterOSAPI({ host: '192.168.88.1', user: 'admin', password: '' }); conn.connect().then(() => { // Create a stream using event listeners const stream = conn.writeStream('/interface/monitor-traffic', [ '=interface=ether1', '=once=' ]); stream.on('data', (packet) => { console.log('Received data:', packet); // packet = { 'rx-bits-per-second': '1234', 'tx-bits-per-second': '5678', ... } }); stream.on('trap', (error) => { console.error('Trap received:', error.message); }); stream.on('done', () => { console.log('Command completed'); }); stream.on('close', () => { console.log('Stream closed'); conn.close(); }); }); ``` -------------------------------- ### Configure Custom Keepalive Command Source: https://context7.com/jace254/node-routeros-v2/llms.txt Use `keepaliveBy()` to set a custom command for maintaining the connection, preventing timeouts. This example uses `/system/resource/print` and logs system status. ```typescript import { RouterOSAPI } from 'node-routeros'; const conn = new RouterOSAPI({ host: '192.168.88.1', user: 'admin', password: '', timeout: 30, keepalive: false // Disable default keepalive }); conn.connect().then(() => { // Use system resource check as keepalive command conn.keepaliveBy('/system/resource/print', (err, data) => { if (err) { console.error('Keepalive error:', err.message); return; } console.log('System status:', { uptime: data[0].uptime, cpuLoad: data[0]['cpu-load'], freeMemory: data[0]['free-memory'] }); }); // Connection will now periodically run /system/resource/print // to stay alive and report system status }); ``` -------------------------------- ### Control Stream Playback with pause(), resume(), and stop() Source: https://context7.com/jace254/node-routeros-v2/llms.txt Manage real-time data streams using RStream control methods. pause() halts reception, resume() continues a paused stream, and stop() permanently ends it. All methods return Promises. This example demonstrates pausing, resuming, and stopping a torch stream. ```typescript import { RouterOSAPI } from 'node-routeros'; const conn = new RouterOSAPI({ host: '192.168.88.1', user: 'admin', password: '' }); conn.connect().then(() => { const stream = conn.stream('/tool/torch', [ '=interface=ether1' ], (err, data) => { if (!err) console.log('Data:', data); }); // Pause after 5 seconds setTimeout(() => { stream.pause() .then(() => console.log('Paused - no more data until resumed')) .catch((err) => console.error('Cannot pause:', err.message)); }, 5000); // Resume after 10 seconds setTimeout(() => { stream.resume() .then(() => console.log('Resumed - data flowing again')) .catch((err) => console.error('Cannot resume:', err.message)); }, 10000); // Stop completely after 20 seconds setTimeout(() => { stream.stop() .then(() => { console.log('Stream stopped permanently'); conn.close(); }) .catch((err) => console.error('Cannot stop:', err.message)); }, 20000); }); ``` -------------------------------- ### connect() Source: https://context7.com/jace254/node-routeros-v2/llms.txt Establishes a connection to the RouterOS device. Returns a Promise that resolves on success or rejects on failure. ```APIDOC ## connect() Establishes a connection to the RouterOS device and authenticates using the provided credentials. Returns a Promise that resolves with the RouterOSAPI instance on successful connection or rejects with an error on failure. ```typescript import { RouterOSAPI } from 'node-routeros'; const conn = new RouterOSAPI({ host: '192.168.88.1', user: 'admin', password: 'secret' }); conn.connect() .then((api) => { console.log('Connected successfully to', api.host); // Connection is now ready for commands // api.connected === true }) .catch((err) => { console.error('Connection failed:', err.message); // Common errors: CANTLOGIN, SOCKTMOUT, ECONNREFUSED }); ``` ``` -------------------------------- ### RouterOSAPI Constructor Source: https://context7.com/jace254/node-routeros-v2/llms.txt Initialize a new RouterOSAPI connection instance with host, user, password, and optional configuration. ```APIDOC ## RouterOSAPI Constructor Creates a new connection instance with credentials and configuration options for connecting to a Mikrotik device. The options include host address, username, password, port (default 8728), timeout in seconds (default 10), TLS configuration, and keepalive setting. ```typescript import { RouterOSAPI } from 'node-routeros'; // Basic connection configuration const conn = new RouterOSAPI({ host: '192.168.88.1', user: 'admin', password: 'secret', port: 8728, // API port (default: 8728, TLS: 8729) timeout: 10, // Connection timeout in seconds keepalive: true // Keep connection alive when idle }); // TLS/SSL encrypted connection const secureConn = new RouterOSAPI({ host: '192.168.88.1', user: 'admin', password: 'secret', tls: { rejectUnauthorized: false // Accept self-signed certificates } }); ``` ``` -------------------------------- ### Listen and Control Data Streams Source: https://github.com/jace254/node-routeros-v2/blob/development/README.md Demonstrates how to listen to data streams from a RouterOS device (e.g., /tool/torch), and use pause, resume, and stop functionalities. The stream object returned by `conn.stream` allows for stream control. ```javascript const RosApi = require("node-routeros").RouterOSAPI; const conn = new RosApi({ host: "192.168.88.1", user: "admin" password: "" }); conn.connect().then(() => { // Counter to trigger pause/resume/stop let i = 0; // The stream function returns a Stream object which can be used to pause/resume/stop the stream const addressStream = conn.stream(['/tool/torch', '=interface=ether1'], (error, packet) => { // If there is any error, the stream stops immediately if (!error) { console.log(packet); // Increment the counter i++; // if the counter hits 30, we stop the stream if (i === 30) { // Stopping the stream will return a promise addressStream.stop().then(() => { console.log('should stop'); // Once stopped, you can't start it again conn.close(); }).catch((err) => { console.log(err); }); } else if (i % 5 === 0) { // If the counter is multiple of 5, we will pause it addressStream.pause().then(() => { console.log('should be paused'); // And after it is paused, we resume after 3 seconds setTimeout(() => { addressStream.resume().then(() => { console.log('should resume'); }).catch((err) => { console.log(err); }); }, 3000); }).catch((err) => { console.log(err); }); } }else{ console.log(error); } }); }).catch((err) => { // Got an error while trying to connect console.log(err); }); ``` -------------------------------- ### Update Connection Options Source: https://context7.com/jace254/node-routeros-v2/llms.txt Use `setOptions()` to modify connection parameters like host, credentials, or port before the next `connect()` call. This allows switching to a backup router. ```typescript import { RouterOSAPI } from 'node-routeros'; const conn = new RouterOSAPI({ host: '192.168.88.1', user: 'admin', password: '' }); conn.connect() .then(() => { console.log('Connected to primary router'); return conn.close(); }) .then(() => { // Switch to backup router conn.setOptions({ host: '192.168.88.2', user: 'admin', password: 'backup-pass', port: 8728, timeout: 15 }); return conn.connect(); }) .then(() => { console.log('Connected to backup router'); }) .catch((err) => { console.error('Connection error:', err.message); }); ``` -------------------------------- ### Initialize RouterOSAPI Connection Source: https://context7.com/jace254/node-routeros-v2/llms.txt Create a new connection instance for a Mikrotik device. Configure host, user, password, port, timeout, and TLS options. Supports basic and secure TLS connections. ```typescript import { RouterOSAPI } from 'node-routeros'; // Basic connection configuration const conn = new RouterOSAPI({ host: '192.168.88.1', user: 'admin', password: 'secret', port: 8728, // API port (default: 8728, TLS: 8729) timeout: 10, // Connection timeout in seconds keepalive: true // Keep connection alive when idle }); // TLS/SSL encrypted connection const secureConn = new RouterOSAPI({ host: '192.168.88.1', user: 'admin', password: 'secret', tls: { rejectUnauthorized: false // Accept self-signed certificates } }); ``` -------------------------------- ### write() - Execute Commands Source: https://context7.com/jace254/node-routeros-v2/llms.txt Executes a RouterOS API command and returns a Promise with the response data. Supports command arguments and query filters. ```APIDOC ## write() Executes a RouterOS API command and returns a Promise with the response data. The first parameter is the command path, followed by optional parameter arrays for command arguments and query filters. ```typescript import { RouterOSAPI } from 'node-routeros'; const conn = new RouterOSAPI({ host: '192.168.88.1', user: 'admin', password: '' }); conn.connect().then(() => { // Add an IP address to an interface conn.write('/ip/address/add', [ '=interface=ether2', '=address=192.168.90.1/24' ]) .then((data) => { console.log('Address added, ID:', data[0].ret); // data = [{ ret: '*1' }] // Query addresses with a filter return conn.write('/ip/address/print', [ '?interface=ether2' ]); }) .then((addresses) => { console.log('Addresses found:', addresses); // addresses = [{ '.id': '*1', address: '192.168.90.1/24', interface: 'ether2', ... }] // Remove the address using its ID return conn.write('/ip/address/remove', [ '=.id=' + addresses[0]['.id'] ]); }) .then(() => { console.log('Address removed successfully'); conn.close(); }) .catch((err) => { console.error('Command error:', err.message); }); }); ``` ``` -------------------------------- ### Add, Print, and Remove IP Address Source: https://github.com/jace254/node-routeros-v2/blob/development/README.md Demonstrates connecting to a RouterOS device, adding an IP address to an interface, printing its details, and then removing it. Ensure the host, user, and password are set correctly. ```javascript const RosApi = require('node-routeros').RouterOSAPI; const conn = new RosApi({ host: '192.168.88.1', user: 'admin', password: '', }); conn.connect() .then(() => { // Connection successful // Let's add an IP address to ether2 conn.write('/ip/address/add', [ '=interface=ether2', '=address=192.168.90.1', ]) .then((data) => { console.log('192.168.90.1 added to ether2!', data); // Added the ip address, let's print it return conn.write('/ip/address/print', ['?.id=' + data[0].ret]); }) .then((data) => { console.log('Printing address info: ', data); // We got the address added, let's clean it up return conn.write('/ip/address/remove', ['=.id=' + data[0]['.id']], ); }) .then((data) => { console.log('192.168.90.1 as removed from ether2!', data); // The address was removed! We are done, let's close the connection conn.close(); }) .catch((err) => { // Oops, got an error console.log(err); }); }) .catch((err) => { // Got an error while trying to connect console.log(err); }); ``` -------------------------------- ### Connect to RouterOS Device Source: https://context7.com/jace254/node-routeros-v2/llms.txt Establish a connection to the RouterOS device using the RouterOSAPI instance. Handles authentication and provides feedback on success or failure. Common errors include CANTLOGIN, SOCKTMOUT, and ECONNREFUSED. ```typescript import { RouterOSAPI } from 'node-routeros'; const conn = new RouterOSAPI({ host: '192.168.88.1', user: 'admin', password: 'secret' }); conn.connect() .then((api) => { console.log('Connected successfully to', api.host); // Connection is now ready for commands // api.connected === true }) .catch((err) => { console.error('Connection failed:', err.message); // Common errors: CANTLOGIN, SOCKTMOUT, ECONNREFUSED }); ``` -------------------------------- ### setOptions() - Update Connection Options Source: https://context7.com/jace254/node-routeros-v2/llms.txt Updates connection parameters without recreating the RouterOSAPI object. Useful for changing host, credentials, or other settings before reconnecting. Changes take effect on the next connect() call. ```APIDOC ## setOptions() ### Description Updates connection parameters without recreating the RouterOSAPI object. Useful for changing host, credentials, or other settings before reconnecting. Changes take effect on the next connect() call. ### Method `setOptions(options: RouterOSAPIConfig): void` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - **options** (RouterOSAPIConfig) - Required - An object containing the new connection options. This can include `host`, `user`, `password`, `port`, `timeout`, `keepalive`, etc. ### Request Example ```typescript import { RouterOSAPI } from 'node-routeros'; const conn = new RouterOSAPI({ host: '192.168.88.1', user: 'admin', password: '' }); conn.connect() .then(() => { console.log('Connected to primary router'); return conn.close(); }) .then(() => { // Switch to backup router conn.setOptions({ host: '192.168.88.2', user: 'admin', password: 'backup-pass', port: 8728, timeout: 15 }); return conn.connect(); }) .then(() => { console.log('Connected to backup router'); }) .catch((err) => { console.error('Connection error:', err.message); }); ``` ### Response None (This method modifies the internal state of the RouterOSAPI object.) ``` -------------------------------- ### Event Handling - Connection State Events Source: https://context7.com/jace254/node-routeros-v2/llms.txt The RouterOSAPI class extends EventEmitter and emits events for connection state changes. Listen for 'error', 'close', and 'timeout' events to handle connection issues gracefully. ```APIDOC ## Event Handling ### Description The RouterOSAPI class extends EventEmitter and emits events for connection state changes. Listen for 'error', 'close', and 'timeout' events to handle connection issues gracefully. ### Events - **'error'**: Emitted when a connection error occurs. - **'close'**: Emitted when the connection is closed. - **'timeout'**: Emitted when the connection times out. ### Method `on(event: string, listener: (...args: any[]) => void): this` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```typescript import { RouterOSAPI } from 'node-routeros'; const conn = new RouterOSAPI({ host: '192.168.88.1', user: 'admin', password: '' }); // Handle connection errors conn.on('error', (err) => { console.error('Connection error:', err.message); // Attempt reconnection after delay setTimeout(() => { conn.connect().catch(console.error); }, 5000); }); // Handle connection close conn.on('close', () => { console.log('Connection closed'); }); conn.connect() .then(() => { console.log('Connected, monitoring connection state...'); }) .catch((err) => { console.error('Initial connection failed:', err.message); }); ``` ### Response None (Event listeners do not return a value directly; they execute callback functions when events are emitted.) ``` -------------------------------- ### Import RouterOSAPI in TypeScript Source: https://github.com/jace254/node-routeros-v2/blob/development/README.md Import the RouterOSAPI class for use in TypeScript projects. ```typescript import { RouterOSAPI } from 'node-routeros'; ``` -------------------------------- ### close() - Graceful Connection Closure Source: https://context7.com/jace254/node-routeros-v2/llms.txt Gracefully closes the connection to the RouterOS device. Stops all active streams, clears keepalive timers, and releases resources. Returns a Promise that resolves when the connection is fully closed. ```APIDOC ## close() ### Description Gracefully closes the connection to the RouterOS device. Stops all active streams, clears keepalive timers, and releases resources. Returns a Promise that resolves when the connection is fully closed. ### Method `close(): Promise` ### Parameters None ### Request Example ```typescript import { RouterOSAPI } from 'node-routeros'; const conn = new RouterOSAPI({ host: '192.168.88.1', user: 'admin', password: '' }); conn.connect() .then(() => { return conn.write('/system/identity/print'); }) .then((data) => { console.log('Router identity:', data[0].name); // Close connection when done return conn.close(); }) .then(() => { console.log('Connection closed'); // conn.connected === false // Can call conn.connect() again to reconnect }) .catch((err) => { console.error('Error:', err.message); }); ``` ### Response - **Promise** - Resolves when the connection is fully closed. ``` -------------------------------- ### Gracefully Close RouterOS Connection Source: https://context7.com/jace254/node-routeros-v2/llms.txt The `close()` method ensures a clean disconnection by stopping streams and clearing timers. It returns a Promise that resolves upon completion. ```typescript import { RouterOSAPI } from 'node-routeros'; const conn = new RouterOSAPI({ host: '192.168.88.1', user: 'admin', password: '' }); conn.connect() .then(() => { return conn.write('/system/identity/print'); }) .then((data) => { console.log('Router identity:', data[0].name); // Close connection when done return conn.close(); }) .then(() => { console.log('Connection closed'); // conn.connected === false // Can call conn.connect() again to reconnect }) .catch((err) => { console.error('Error:', err.message); }); ``` -------------------------------- ### keepaliveBy() - Custom Keepalive Source: https://context7.com/jace254/node-routeros-v2/llms.txt Configures a custom command to keep the connection alive instead of the default idle command. Useful for monitoring specific data while preventing connection timeout. Accepts command parameters and an optional callback for processing responses. ```APIDOC ## keepaliveBy() ### Description Configures a custom command to keep the connection alive instead of the default idle command. Useful for monitoring specific data while preventing connection timeout. Accepts command parameters and an optional callback for processing responses. ### Method `keepaliveBy(command: string, callback?: (err: Error | null, data?: any) => void): void` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```typescript import { RouterOSAPI } from 'node-routeros'; const conn = new RouterOSAPI({ host: '192.168.88.1', user: 'admin', password: '', timeout: 30, keepalive: false // Disable default keepalive }); conn.connect().then(() => { // Use system resource check as keepalive command conn.keepaliveBy('/system/resource/print', (err, data) => { if (err) { console.error('Keepalive error:', err.message); return; } console.log('System status:', { uptime: data[0].uptime, cpuLoad: data[0]['cpu-load'], freeMemory: data[0]['free-memory'] }); }); // Connection will now periodically run /system/resource/print // to stay alive and report system status }); ``` ### Response None (This method configures keepalive behavior and does not return a direct response in the traditional sense. The callback handles potential errors or data from the keepalive command.) #### Success Response (N/A) #### Response Example (See Request Example for callback data structure) ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.