Filesystem
Leia, escreva e gerencie arquivos dentro de volumes de filesystem em sandbox.
Para configuração de filesystem, veja Filesystem.
Carregamento
local fs = require("fs")
Adquirindo um Volume
Obter um volume de filesystem por ID do registro:
local vol, err = fs.get("app:storage")
if err then
return nil, err
end
local content = vol:readfile("/config.json")
| Parâmetro | Tipo | Descrição |
|---|---|---|
name |
string | ID do volume no registro |
Retorna: FS, error
Lendo Arquivos
Ler conteudo completo do arquivo:
local vol = fs.get("app:config")
local data, err = vol:readfile("/settings.json")
if err then
return nil, err
end
local config = json.decode(data)
Para arquivos grandes, use streaming com open():
local file = vol:open("/data/large.csv", "r")
while true do
local chunk = file:read(65536)
if not chunk or #chunk == 0 then break end
process(chunk)
end
file:close()
Escrevendo Arquivos
Escrever dados em um arquivo:
local vol = fs.get("app:data")
-- Sobrescrever (padrão)
vol:writefile("/config.json", json.encode(config))
-- Anexar
vol:writefile("/logs/app.log", message .. "\n", "a")
-- Escrita exclusiva (falha se existe)
local ok, err = vol:writefile("/lock.pid", tostring(pid), "wx")
| Modo | Descrição |
|---|---|
"w" |
Sobrescrever (padrão) |
"a" |
Anexar |
"wx" |
Escrita exclusiva (falha se arquivo existe) |
Para escritas em streaming:
local file = vol:open("/output/report.txt", "w")
file:write("Header\n")
file:write("Data: " .. value .. "\n")
file:sync()
file:close()
Verificando Caminhos
local vol = fs.get("app:data")
-- Verificar existencia
if vol:exists("/cache/results.json") then
return vol:readfile("/cache/results.json")
end
-- Verificar se e diretorio
if vol:isdir(path) then
process_directory(path)
end
-- Obter informacoes do arquivo
local info = vol:stat("/documents/report.pdf")
print(info.size, info.modified, info.type)
Campos de stat: name, size, mode, modified, is_dir, type
Operações de Diretorio
local vol = fs.get("app:data")
-- Criar diretorio
vol:mkdir("/uploads/" .. user_id)
-- Listar conteudo do diretorio
for entry in vol:readdir("/documents") do
print(entry.name, entry.type)
end
-- Remover arquivo ou diretorio vazio
vol:remove("/temp/file.txt")
Campos de entrada: name, type ("file" ou "directory")
Métodos de File Handle
Ao usar vol:open() para streaming:
| Método | Descrição |
|---|---|
read(size?) |
Ler bytes (padrão: 4096) |
write(data) |
Escrever dados string |
seek(whence, offset) |
Definir posicao ("set", "cur", "end") |
sync() |
Flush para armazenamento |
close() |
Liberar file handle |
scanner(split?) |
Criar scanner de linha/palavra |
Sempre chame close() ao terminar com um file handle.
Scanner
Para processamento linha por linha:
local file = vol:open("/data/users.csv", "r")
local scanner = file:scanner("lines")
scanner:scan() -- pular header
while scanner:scan() do
local line = scanner:text()
process(line)
end
file:close()
Modos de split: "lines" (padrão), "words", "bytes", "runes"
Constantes
fs.type.FILE -- "file"
fs.type.DIR -- "directory"
fs.seek.SET -- do inicio
fs.seek.CUR -- do atual
fs.seek.END -- do fim
Métodos FS
| Método | Retorna | Descrição |
|---|---|---|
readfile(path) |
string, error |
Ler arquivo inteiro |
writefile(path, data, mode?) |
boolean, error |
Escrever arquivo |
exists(path) |
boolean, error |
Verificar se caminho existe |
stat(path) |
table, error |
Obter info do arquivo |
isdir(path) |
boolean, error |
Verificar se e diretorio |
mkdir(path) |
boolean, error |
Criar diretorio |
remove(path) |
boolean, error |
Remover arquivo/diretorio vazio |
readdir(path) |
iterator |
Listar diretorio |
open(path, mode) |
File, error |
Abrir file handle |
chdir(path) |
boolean, error |
Mudar diretorio de trabalho |
pwd() |
string |
Obter diretorio de trabalho |
Permissões
Acesso ao filesystem está sujeito a avaliação de política de segurança.
| Ação | Recurso | Descrição |
|---|---|---|
fs.get |
ID do Volume | Adquirir volume de filesystem |
Erros
| Condição | Tipo | Retentável |
|---|---|---|
| Caminho vazio | errors.INVALID |
não |
| Modo inválido | errors.INVALID |
não |
| Arquivo fechado | errors.INVALID |
não |
| Caminho não encontrado | errors.NOT_FOUND |
não |
| Caminho ja existe | errors.ALREADY_EXISTS |
não |
| Permissão negada | errors.PERMISSION_DENIED |
não |
Veja Error Handling para trabalhar com erros.