﻿# Example of a common script with server-side dependencies

Пример настройки общего скрипта с серверными зависимостями npm-пакетов в On-Premises: функция конвертации файлов .csv в .xlsx и её вызов на странице.

> [HTML Version](common-scripts-example-npm.html)

In BRIX On-Premises, you can extend server-side scripts functionality by adding server-side npm package dependencies. These are third-party libraries containing ready-made code for common tasks. To avoid adding server dependencies and duplicating code across scripts used in different business processes, widgets, and modules, it is best to configure them in [common scripts](common-scripts.md), which you can then call from other components. 

For example, you may need to convert tables from **.csv ** to **.xlsx** in several business processes, on different forms and pages. To set this up, use the [exceljs](https://www.npmjs.com/package/exceljs) and [readable-web-to-node-stream](https://www.npmjs.com/package/readable-web-to-node-stream)  npm packages, which are imported into a common script. You can then use this script in different components—for example, to configure a page where an employee uploads a **.csv **file, clicks a button, and receives an **.xlsx **file.

This article explains how to upload an archive containing npm packages to a module, configure a file conversion function, and call it from the script of the required component.

## Step 1. Configure a common script with server dependencies

Let’s look at how to configure server dependencies and a function for converting files from **.csv ** to **.xlsx**:

1. Create an archive containing the server dependencies in the **exceljs** and **readable-web-to-node-stream ** npm packages, as described in [Server dependencies in npm packages](npm-package.md).  
  
This creates an archive named **dependencies.tar.gz**.

2. Create a custom module named **Working with files** and add a common script named **File conversion**.

3. On the common script settings page, open the **Files** tab and upload the prepared dependencies archive.

4. On the **Scripts** tab, import the functionality from the archive using the standard TypeScript syntax:

````
import \* as Excel from 'exceljs';  
import \* as rw2n from 'readable-web-to-node-stream';

````
where:

- **\*** imports all package contents, including methods, classes, interfaces, and constants. You can also import an individual component by replacing the asterisk with its name.

- `Excel`,` rw2n`** ** are aliases assigned to the packages in the current script. Use them to access the packages’ methods, classes, and etc.

- `'exceljs', 'readable-web-to-node-stream'` are the package names in the **dependencies.tar.gz**.

5. On the **Types** tab, add a custom type named `XlsBuffer` to store the converted file contents as binary data. It extends the standard TypeScript  `ArrayBuffer `type:

````
export interface XlsBuffer extends ArrayBuffer \{\}

6. ````
On the **Functions** tab, create a function named **Converting csv to xlsx **(`csv2xlsx`) and add the following parameters:

- An input parameter **File ID** (`fileId`) with the **String **type field. It passes the ID of the **.csv** file to convert.

- An output parameter **Conversion result** (`buffer`) with the **Any type** type field. In its settings, select the custom type `XlsBuffer` you added earlier. It stores the converted file contents as binary data.

7. On the **Scripts** tab, you will see the function signature that was added automatically. It includes its name, parameters, and return value. Implement the function logic:

````
export async function csv2xlsx(input?: Function\$csv2xlsx\$Input\$Args): Promise<Function\$csv2xlsx\$Output\$Args> \{  
 const fileId = input?.fileId;  
 if (\!fileId) \{  
 throw new Error('File ID is missing');  
 \}  
 const csvFileItem = await System.files.search().where(f => f.\_\_id.eq(fileId)).first();  
 if (\!csvFileItem) \{  
 throw new Error('File not found);  
 \}  
 const url = await csvFileItem.getDownloadUrl();  
 const fetchResult = await fetch(url);  
 if (fetchResult.status >= 300) \{  
 throw new Error(fetchResult.statusText ?? 'Error retrieving the file');  
 \}  
 const workbook = new Excel.Workbook();  
 const rwn = new rw2n.ReadableWebToNodeStream(fetchResult.body\!);  
 const worksheet = await workbook.csv.read(rwn);  
 const buf: ArrayBuffer = await workbook.xlsx.writeBuffer();  
 return \{  
 buffer: buf,  
 \};  
\}

8. ````
Save and publish the common script.

You can now use the configured common script function in server-side scripts of other system components.

## Step 2. Call a common script with a server-side dependency

As an example, let’s see how to use the common script on a page so that users can upload a table in **.csv** and receive the converted file in **.xlsx**:

1. Create a page named **Converting csv to xlsx** and open it in the interface designer.

2. On the **Context** tab, add two fields of **Files (one) **type:

- **.csv file** (`csv\_file`) for uploading the source file.

- **Result** (`result\_file`) for displaying the conversion result.

3. Place these fields on the page. For the **Result** field, enable the following options: **Read only** and **Hide if the field is empty**.

**(common-scripts-example-npm-1.png)**

4. Add a **Button** widget to the page and set its action type to **Script**. In the **Executed script** field, create a function named `on\_convert\_button\_click()` and save the widget settings.

**(common-scripts-example-npm-2.png)**

5. Open the **Settings > Available Items** tab and add an optional dependency on the **Working with files** module by clicking **+ Add Workspace**.

6. Click the book icon **(library-icon.png)** next to the module name, then select the common script **File conversion**.

7.  In the list of dependencies, assign descriptive aliases to the module and common script. You will use these aliases to reference them in the script.

**(common-scripts-example-npm-3.png)**



8. Go to the **Scripts** tab, import the common script using the following syntax:

````
import api\_utils from 'files\_processing/converter';

````
where `'files\_processing/converter'` are the aliases assigned to the module and common script.

You can now access the common script function through the object named `api\_utils`.

9. On the **Scripts** tab, write a function that uses the common script to convert the table to **.xlsx**, then saves the resulting file to the **Result** field (`result\_file`):

````
async function on\_convert\_button\_click(): Promise<void> \{  
 const fileID = Context.data.csv\_file\!.id;  
  
 const utils = api\_utils\!;  
 const convertResult = await utils.csv2xlsx(\{fileId: fileID\});  
 if (\!convertResult?.buffer) \{  
 throw new Error('Error while converting');  
 \}  
 Context.data.result\_file = await Context.fields.result\_file.create('result.xlsx', convertResult.buffer);  
\}



10. ````
Save and publish the page.

Employees can now use the **Converting csv to xlsx** page to convert tables to **.xlsx** for further use.

You can call this conversion function in the same way from any other system component.

