HarmonyOS fs 文件操作中如何判断 给出的路径是文件还是文件夹?

let file = './test' 

fs.accessSync(file) 只能判断file 是否存在吧,file 是文件夹还是文件这个怎么判断

阅读 486
1 个回答

isDirectory:用于判断文件是否是目录

let dirPath = pathDir + ""/test"";
let isDirectory = fs.statSync(dirPath).isDirectory(); 

参考文档:

https://developer.huawei.com/consumer/cn/doc/harmonyos-references-V5/js-apis-fileio-V5\#isdirectory

isFile:用于判断文件是否是普通文件

let filePath = pathDir + ""/test.txt"";
let isFile = fs.statSync(filePath).isFile();

参考文档:

https://developer.huawei.com/consumer/cn/doc/harmonyos-references-V5/js-apis-fileio-V5\#isfile

async readLocalFileWithStream() {
  try {
    // 存储每次读取的结果
    let buffers: buffer.Buffer[] = [];
    // 打开文件流
    let inputStream = fs.createStreamSync(""文件沙箱路径"", 'r+');
    // 以流的形式读取源文件内容
    let bufSize = 4096;
    let readSize = 0;
    let buf = new ArrayBuffer(bufSize);

    class Option {
      public offset: number = 0;
      public length: number = bufSize;
    }

    let option = new Option();
    option.offset = readSize;
    let readLen = await inputStream.read(buf, option);
    // 存储当前读取结果
    buffers.push(buffer.from(buf.slice(0, readLen)))
    readSize += readLen;
    while (readLen > 0) {
      option.offset = readSize;
      readLen = await inputStream.read(buf, option);
      // 存储当前读取结果
      buffers.push(buffer.from(buf.slice(0, readLen)))
      readSize += readLen;
    }
    // 关闭文件流
    inputStream.closeSync();
    // 合并内容
    let finalBuf: ArrayBuffer = buffer.concat(buffers).buffer
    console.info(`final ArrayBuffer byteLength is ${finalBuf.byteLength}}`)
  } catch (error) {
    let err = error as BusinessError;
    console.error(`readLocalFileWithStream failed, code is ${err.code},message is ${err.message}`);
  }
}
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
logo
HarmonyOS
子站问答
访问
宣传栏