Filesystem
Filesystem
Seção intitulada “Filesystem”Leia, escreva e gerencie arquivos dentro de volumes de filesystem em sandbox.
Para configuração de filesystem, veja Filesystem.
Carregamento
Seção intitulada “Carregamento”local fs = require("fs")Adquirindo um Volume
Seção intitulada “Adquirindo um Volume”Obter um volume de filesystem por ID do registro:
local vol, err = fs.get("app:storage")if err then return nil, errend
local content = vol:readfile("/config.json")| Parâmetro | Tipo | Descrição |
|---|---|---|
name | string | ID do volume no registro |
Retorna: FS, error
Lendo Arquivos
Seção intitulada “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, errend
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
Seção intitulada “Escrevendo Arquivos”Escrever dados em um arquivo:
local vol = fs.get("app:data")
-- Sobrescrever (padrão)vol:writefile("/config.json", json.encode(config))
-- Anexarvol: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
Seção intitulada “Verificando Caminhos”local vol = fs.get("app:data")
-- Verificar existenciaif vol:exists("/cache/results.json") then return vol:readfile("/cache/results.json")end
-- Verificar se e diretorioif vol:isdir(path) then process_directory(path)end
-- Obter informacoes do arquivolocal 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
Seção intitulada “Operações de Diretorio”local vol = fs.get("app:data")
-- Criar diretoriovol:mkdir("/uploads/" .. user_id)
-- Listar conteudo do diretoriofor entry in vol:readdir("/documents") do print(entry.name, entry.type)end
-- Remover arquivo ou diretorio vaziovol:remove("/temp/file.txt")Campos de entrada: name, type (“file” ou “directory”)
Métodos de File Handle
Seção intitulada “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”) |
stat() | Obter info do arquivo (mesmos campos de vol:stat) |
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
Seção intitulada “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
Seção intitulada “Constantes”fs.type.FILE -- "file"fs.type.DIR -- "directory"
fs.seek.SET -- do iniciofs.seek.CUR -- do atualfs.seek.END -- do fimMétodos FS
Seção intitulada “Métodos FS”| Método | Retorna | Descrição |
|---|---|---|
readfile(path) / read_file(path) | string, error | Ler arquivo inteiro |
writefile(path, data, mode?) / write_file(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, error | Obter diretorio de trabalho |
Permissões
Seção intitulada “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 |
| 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.