【问题标题】:Why readFile of react-native-fs only read part of a text file?为什么 react-native-fs 的 readFile 只读取文本文件的一部分?
【发布时间】:2019-05-24 00:44:22
【问题描述】:

我尝试使用 react-native-fs readFile 函数从文本文件中读取,结果字符串总是以某些字符结尾。

我已经更改了文本文件的内容,它仍然在 4094 个字符后结束。

  await RNFS.readFile(p, 'utf8')
    .then((readresult) => {
    console.log(readresult);
    res = {success: true, contents: readresult};
  })
  .catch((err) => {
    console.log('ERROR' + err.message);
    res = {success: false, errorMsg: err.message};
  })

日志总是产生前 4094 个字符。

【问题讨论】:

    标签: react-native readfile react-native-fs


    【解决方案1】:

    您可以尝试使用read 逐个读取文件:

    // We'll call this function multiple times to read the file in chunks.
    // Feel free to append additional error handling and logging to this function.
    const readChunk = (file, length, position) => {
      return RNFS.read(file, length, position, 'utf8');
    }
    
    // Set the number of character to read in each chunk
    const length = 4094;
    let chunk = '';
    let total = '';
    
    // Add together the chunks as you read them.
    // When the next chunk is empty, you've reached the end of the file.
    do {
      chunk = await readChunk(p, length, total.length);
      total += chunk;
    } while (chunk.length > 0);
    

    【讨论】:

      猜你喜欢
      • 2018-05-29
      • 1970-01-01
      • 1970-01-01
      • 2013-05-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多