跳到主要内容

fs 文件系统

fs 是 Alia 的标准库文件系统模块,提供文件的读写、复制、重命名、删除等操作。

引入模块​

import 'fs' as fs ~ 导入为变量
import 'fs' ~ 导入作用域

方法​

read​

read 读取文件内容并返回 String。

const content = fs.read 'hello.txt'
print content

文件不存在时抛出错误。

write​

write 将内容写入文件,目标目录不存在时自动创建。

fs.write 'Hello, Alia!' to 'output.txt'

rename​

rename 重命名或移动文件。

fs.rename 'old.txt' to 'new.txt'

remove​

remove 删除文件,文件不存在时抛出错误。

fs.remove 'temp.txt'

copy​

copy 复制文件,目标目录不存在时自动创建。

fs.copy 'source.txt' to 'backup.txt'

stat​

stat 获取文件信息并返回 Object,包含以下属性:

属性类型说明
sizeNumber文件大小(字节)
isFileBoolean是否为文件
isDirectoryBoolean是否为目录
modifiedString最后修改时间(ISO 8601)
const info = fs.stat 'hello.txt'
print info.size ~ 输出文件大小
print info.isFile ~ 输出 true
print info.isDirectory ~ 输出 false

exist​

exist 判断文件是否存在并返回 Boolean。

if fs.exist 'config.json' {
const config = fs.read 'config.json'
print config
}

list​

list 枚举目录的直接子项名,返回已排序的 Array。子项含文件与目录,目录不以特殊字符标记。

const names = fs.list 'src'
each name in names {
print name
}

listRecursive​

listRecursive 递归枚举目录,返回相对入参 path 的已排序 Array。目录项以 / 结尾,路径分隔符固定为 /,与宿主平台的路径分隔符无关。

const files = fs.listRecursive '.'
each rel in files {
if rel.endsWith '.alia' {
print rel
}
}

排序与分隔符固定是刻意约定:编译器枚举源码树、Analyzer 建立工作区索引、ModSpace 打包都需要跨目标与跨运行一致的结果。

两种方法在路径不存在、非目录或无读权限时抛出 FS_LIST_FAILED。

示例代码​

import 'fs' as fs

const demoPath = '/tmp/demo.txt'
const copyPath = '/tmp/demo_copy.txt'
const renamedPath = '/tmp/demo_renamed.txt'

~ 写入文件
fs.write 'Hello, Alia!' to demoPath

~ 读取文件
const content = fs.read demoPath
print content

~ 检查文件是否存在
assert fs.exist demoPath error '文件应存在'

~ 获取文件信息
const info = fs.stat demoPath
print info.size

~ 复制文件
fs.copy demoPath to copyPath

~ 重命名文件
fs.rename copyPath to renamedPath

~ 删除文件
fs.remove demoPath
fs.remove renamedPath

下一步​