function that list inport names of simulink model in javascript

To list the names of simulink models using JavaScript one must use the Simulink API (Application Programming interface) with the help of Node.js. Below is an example of how to do it:

index.tsx
// Importing Required Libraries and Initializing Variables
const path = require('path');
const Simulink = require('simulink-connection');
const simulink = new Simulink();
const modelPath = path.join(__dirname, '/Models');

// Setting Configuration Options
simulink.config({
    host: 'localhost',
    port: 17725,
    modelPath,
});

// Connecting to Simulink
simulink.connect()
    .then(() => {
        // Fetching List of Models
        simulink.getModels()
            .then((models) => {
                console.log(models);
            })
            .catch((err) => {
                console.log(`Error Occured while fetching list of models: ${err}`);
            })
            .finally(() => {
                // Disconnecting from Simulink
                simulink.disconnect();
            });
    })
    .catch((err) => {
        console.log(`Error Occured while connecting to Simulink: ${err}`);
    });
917 chars
33 lines

The above code does the following steps:

  1. Importing Required Libraries and Initializing Variables

    • path module is used to help with working with file paths
    • simulink-connection is the Node.js Simulink API library that provides the capability to connect and work with Simulink
    • simulink is an instance of Simulink class that we will use to connect to Simulink
    • modelPath is the path for the directory containing the simulink models that we want to obtain
  2. Setting Configuration Options

    • We are setting up the configuration options for the simulink instance that we have created above. These options are such as to specify the host and port number to which we want to connect our Simulink instance.
  3. Connecting to Simulink

    • We will establish a connection to Simulink by calling the connect() function on our simulink instance
    • If connection is established, we move to the next step, else we print the error message.
  4. Fetching List of Models

    • We will call getModels() function to fetch the list of models, which will return a Promise with the list of models, which we store in models array.
    • If there is any error while fetching the model list, we print the error message.
  5. Finally Disconnecting from Simulink

    • We always want to ensure that we disconnect from the simulink instance after communicating with the Simulink API, hence we finally call the disconnect() function of our simulink instance.

The above example code can also be extended further to do any other additional stuff with the fetched Simulink model list.

gistlibby LogSnag