# get()

Canonical URL: https://developers.iagenify.com/es/sdk/ref/files/get/
Language: es

`api.files.get(sourceId) → Promise<IaGenifyFile>`

Lee un archivo con su contenido. El texto vuelve como una cadena, cualquier otra cosa como bytes — y el objeto está listo para actualizar.

Status: GET /api/files/:id · free · content included

## Parámetros {#parameters}

| Name | Type | Requirement | Description |
| --- | --- | --- | --- |
| `sourceId` | string | obligatorio | Desde [guardar()](/es/sdk/ref/files/save) o [list()](/es/sdk/ref/files/list). Falta → el SDK lanza. |

## Valor devuelto {#returns}

```javascript
const file = await api.files.get(sourceId);

file.name;       // "report.md"
file.mimeType;   // "text/markdown"
file.content;    // a string, here — a Buffer for binary
file.sourceId;   // set, so update() works straight away
file.location;   // the kind of storage it is in
file.metadata;   // { size, mimeType, originalName }
```

## Cadena o bytes, decididos por el tipo {#text}

Un archivo cuyo tipo es texto-ish vuelve como una cadena; todo lo demás como un `Buffer`.

| mimeType | contenido |
| --- | --- |
| texto/* · json · xml · yaml · csv · marca de posición · plano | una cadena |
| Imagen/* · audio/* · vídeo/* · pdf · cualquier otra cosa | a Buffer |

```javascript
const file = await api.files.get(sourceId);

if (typeof file.content === "string") {
  console.log(file.content.slice(0, 200));
} else {
  await fs.writeFile(`./${file.name}`, file.content);
}
```

> **La decisión es el tipo, no los bytes**
>
> Un archivo de texto guardado sin un mimeType vuelve como un Buffer. Establece el tipo en create() y esto nunca aparece.

## Lee todo el archivo {#whole}

No hay rango ni streaming: el contenido llega en una respuesta, como texto o como base64 que el SDK Para algo grande, eso es memoria en ambos lados — califíquela antes de buscarla.

```javascript
const files = await api.files.list();
const target = files.find((f) => f.id === sourceId);

if (target.size > 20 * 1024 * 1024) {
  throw new Error(`${target.name} is ${Math.round(target.size / 1e6)} MB — too big to read in one go`);
}

const file = await api.files.get(sourceId);
```

## Errores {#errors}

| Código | Estado | Cuándo |
| --- | --- | --- |
| — (error lanzado localmente) | — | No hay fuente que pase. |
| file_not_found | 404 | No hay ningún archivo de esta cuenta con esa identificación. |
| file_missing_on_disk | 404 | El registro existe y sus bytes no. |

> **file_missing_on_disk vale la pena darse cuenta, no volver a intentarlo**
>
> El registro y los bytes se han separado. Intentar de nuevo responde lo mismo; lo que ayuda es borrar el registro y guardar el archivo de nuevo.

Un archivo que pertenece a otra cuenta responde lo mismo `404`: cada consulta es dirigida al que llama.

- [file.update()](/es/sdk/ref/files/update): El objeto vuelve listo para ello.
- [list()](/es/sdk/ref/files/list): Encontrar una identificación, y un tamaño, antes de leer.

```python
file = api.files.get(source_id)

file.name        # "report.md"
file.mime_type   # "text/markdown"
file.content     # a str, here — bytes for binary
file.source_id   # set, so update() works straight away
file.location    # the kind of storage it is in
file.metadata    # {"size", "mimeType", "originalName"}
```

```python
from pathlib import Path

file = api.files.get(source_id)

if isinstance(file.content, str):
    print(file.content[:200])
else:
    Path(file.name).write_bytes(file.content)
```

```python
files = api.files.list()
target = next(f for f in files if f["id"] == source_id)

if target["size"] > 20 * 1024 * 1024:
    raise ValueError(f"{target['name']} is {round(target['size'] / 1e6)} MB — too big to read in one go")

file = api.files.get(source_id)
```
