Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

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] #247

Open
sagar-capti opened this issue Jan 13, 2025 · 7 comments

Comments

@sagar-capti
Copy link
Contributor

sagar-capti commented Jan 13, 2025

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. ((D:\Projects\test\demo\node_modules\telnet-client\lib\index.js:155:34)
at Socket.emit (node:events:514:28)
at addChunk (node:internal/streams/readable:324:12)
at readableAddChunk (node:internal/streams/readable:297:9)
at Readable.push (node:internal/streams/readable:234:10)
at TCP.onStreamRead (node:internal/stream_base_commons:190:23)
telnetConnection established successfully.
Sending 'enable' command...
Enable command response:
ew07-89log.bne
Sending 'display mac-address port 0/1/0' command...
Response chunk:

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...

@sagar-capti sagar-capti changed the title TypeError [ERR_INVALID_ARG_TYPE]: The "buf" argument must be an instance of Buffer, TypedArray, or DataView. Received null at new NodeError 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] Jan 13, 2025
@rickyraz
Copy link

me too , UP

@sagar-capti
Copy link
Contributor Author

sagar-capti commented Feb 3, 2025

Hi @mkozjak

I have made some changes in the telnet-client lib file in node_modules (node_modules/telnet-client/lib/index.js) as shown in the screenshots

https://prnt.sc/MCevF0y6VGTh

https://prnt.sc/HHD6_SvLL_F9

now it's working for me.

@mkozjak could you please review and update it.

@viniciusnw
Copy link

me too

@mkozjak
Copy link
Owner

mkozjak commented Feb 12, 2025

@sagar-capti nice work. Able to wrap it up into a PR?

@sagar-capti
Copy link
Contributor Author

sagar-capti commented Feb 17, 2025

@sagar-capti nice work. Able to wrap it up into a PR?

I tried to create PR but showing some permission issue.
https://prnt.sc/zFIK5jbuWiz8

@mkozjak

@mkozjak
Copy link
Owner

mkozjak commented Feb 17, 2025

@sagar-capti - Please fork this repo and create a patch in your own. then create a PR. Base will be this repo and the tip will be yours. Thanks!

@sagar-capti
Copy link
Contributor Author

@mkozjak - Done
PR Created.

Thanks!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

4 participants