node-telnet-client
node-telnet-client copied to clipboard
Closed the Server and app crashed [TypeError [ERR_INVALID_ARG_TYPE]: The "buf" argument must be an instance of Buffer, TypedArray, or DataView. Received null at new NodeError]
In version 2.2.2, When attempt a telnet connection, It show an error as below "error: TypeError [ERR_INVALID_ARG_TYPE]: The "buf" argument must be an instance of Buffer, TypedArray, or DataView. Received null"
and executes the properly. and at the end it Closed the Server and my app crashed
"nodemon" version: "^2.0.0",
==Here is the Code function==
const getInterfaceMac = async ({ updatedResult }) => { console.log('updatedResult ==', updatedResult);
const params = { host: '10.6.234.635', port: 23, username: 'demoapi', password: 'ei38uer47rbjkfq', shellPrompt: /[#>]\s*$/, // Matches shell prompt timeout: 30000, loginPrompt: /User name[: ]$/i, passwordPrompt: /password[: ]$/i, debug: true, };
try { console.log('Attempting to connect...'); await telnetConnection.connect(params); console.log('telnetConnection established successfully.');
// Delay to handle any initial prompts
await new Promise((resolve) => setTimeout(resolve, 2000));
// Enter enable mode
console.log("Sending 'enable' command...");
const enableResponse = await telnetConnection.exec('enable');
console.log('Enable command response:', enableResponse);
// If the enable response is unexpected, handle this scenario
if (!enableResponse || enableResponse.includes('error')) {
console.error('Error after enable command, invalid response:', enableResponse);
throw new Error('Failed to enter enable mode.');
}
// Delay to ensure readiness
await new Promise((resolve) => setTimeout(resolve, 2000));
// Loop through each updatedResult item and execute the command
for (let result of updatedResult) {
const port = result.port;
console.log(`Sending 'display mac-address port ${port}' command...`);
try {
// Send the command to get MAC addresses for the port
await telnetConnection.write(`display mac-address port ${port}\n`);
let fullResponse = '';
let morePromptRegex = /---- More \( Press 'Q' to break \) ----/;
let intermediatePromptRegex = /\{\s<cr>\|\|<K>\s\}:/;
while (true) {
// Read a chunk of output
const response = await telnetConnection.send('\n', {
waitfor: /[#>]|---- More \( Press 'Q' to break \) ----|\{\s<cr>\|\|<K>\s\}:/,
});
console.log('Response chunk:', response);
if (response === null || response === undefined) {
console.error('Received invalid response (null/undefined) while waiting for data.');
break;
}
fullResponse += response;
// Check for prompts and send Enter
if (morePromptRegex.test(response) || intermediatePromptRegex.test(response)) {
console.log('Prompt detected, sending Enter...');
await telnetConnection.write('\n');
} else {
// Break the loop when no more prompts are detected
break;
}
}
console.log(`Final MAC Address response for port ${port}:`, fullResponse);
// Extract MAC address data and update the current result
const macAddresses = fullResponse
.split('\n')
.filter((line) => line.includes('dynamic')) // Filter lines with 'dynamic' MAC entries
.map((line) => line.trim()) // Trim extra spaces
.map((line) => {
const parts = line.split(/\s+/); // Split line by spaces
return parts.length > 0 ? parts[0] : null; // Return MAC address if valid
})
.filter(Boolean); // Remove any null or undefined entries
console.log('Extracted MAC Addresses for port:', macAddresses);
// Update the result with the extracted MAC addresses
result.macAddresses = macAddresses;
result.status = 'success'; // Indicating the command executed successfully
} catch (portError) {
console.error(`Error executing command for port ${port}:`, portError);
result.status = 'failed'; // Indicating failure
result.error = portError.message || 'Unknown error'; // Adding error message
}
}
// Close the telnetConnection
telnetConnection.end();
console.log('telnetConnection closed.');
// Return the updated results with MAC addresses or error information
return updatedResult;
} catch (error) { console.error('Error during telnet session:', error); if (telnetConnection) telnetConnection.end(); // Ensure the telnetConnection is closed on error throw error; } }; process.on('unhandledRejection', (error) => { console.log('Do something about it: ', error); throw error; });
=== ERROR ===
Attempting to connect...
error: TypeError [ERR_INVALID_ARG_TYPE]: The "buf" argument must be an instance of Buffer, TypedArray, or DataView. Received null
at new NodeError (node:internal/errors:405:5)
at StringDecoder.write (node:string_decoder:99:11)
at Telnet.parseData (D:\Projects\test\demo\node_modules\telnet-client\lib\index.js:357:45)
at Socket.
ew07-89log.bne# Final MAC Address response for port 0/1/0:
ew07-89log.bne# Extracted MAC Addresses for port: [] Sending 'display mac-address port 0/1/1' command... Response chunk:
ew07-89log.bne# Extracted MAC Addresses for port: [] telnetConnection closed. info: GET /v1/demo/get-interface?appid=d581eef5c4c8df589a4e9 200 - 58513.479 ms info: Server closed [nodemon] app crashed - waiting for file changes before starting...