从客户端读取文本文件并在客户端上超出了javascript中单个字符串的最大大小

2023-12-12

我想反转在 javascript 中在客户端上执行的以下步骤,但在处理 blob 时遇到了问题。

在 indexedDB 数据库中,在对象存储索引上打开的游标上:

  1. 从数据库中提取数据对象。
  2. 使用 JSON.stringify 将对象转换为字符串。
  3. 创建 JSON 字符串的新 blob { type: 'text/csv' }。
  4. 将 blob 写入数组。
  5. 将光标向下移动一位并从步骤 1 开始重复。

事务成功完成后,将从 Blob 数组中生成相同类型的新 Blob。

这样做的原因是 JSON 字符串的串联超出了单个字符串允许的最大大小;因此,无法首先连接并形成一个大字符串的一团。但是,Blob 数组可以制作成更大大小(大约 350MB)的单个 Blob,并下载到客户端磁盘。

为了反转这个过程,我想我可以读入 blob,然后将其分割成组件 blob,然后将每个 blob 作为字符串读取;但我不知道该怎么做。

如果 FileReader 作为文本读取,则结果是一大块文本,无法写入单个变量,因为它超出了最大大小并引发分配大小溢出错误。

看来将文件作为数组缓冲区读取是一种允许将 blob 切成碎片的方法,但似乎存在某种编码问题。

有没有办法按原样反转原始过程,或者可以添加编码步骤以允许将数组缓冲区转换回原始字符串?

我尝试阅读一些似乎相关的问题,但此时我不明白他们正在讨论的编码问题。看来恢复字符串是相当复杂的。

感谢您提供的任何指导。

采用接受的答案后的附加信息

下面发布的代码当然没有什么特别的,但我想我应该把它分享给那些和我一样陌生的人。这是集成到 asnyc 函数中的公认答案,用于读取 blob、解析它们并将它们写入数据库。

此方法使用很少的内存。遗憾的是没有办法将数据写入磁盘。将数据库写入磁盘时,内存使用量会随着大 blob 的生成而增加,并在下载完成后不久释放。使用此方法从本地磁盘上传文件似乎可以工作,而无需在切片之前将整个 blob 加载到内存中。就好像文件是从磁盘中分片读取的。因此,它在内存使用方面非常有效。

就我的具体情况而言,仍有工作要做,因为使用此方法将总计 350MB 的 50,000 个 JSON 字符串写入数据库相当慢,大约需要 7:30 才能完成。

现在,每个单独的字符串都被单独切片,作为文本读取,并在单个事务中写入数据库。将 blob 切成由一组 JSON 字符串组成的更大块,将它们作为块中的文本读取,然后在单个事务中将它们写入数据库,是否会执行得更快,同时仍然不使用大量内存,这是一个问题我需要尝试一个单独问题的主题。

如果使用替代循环来确定填充大小 const c 所需的 JSON 字符串数量,然后对该大小的 blob 进行切片,将其作为文本读取,并将其拆分以解析每个单独的 JSON 字符串,则完成时间约为 1 :30(对于 c =250,000 至 1,000,000)。无论如何,解析大量 JSON 字符串似乎仍然会减慢速度。大 blob 切片不会转换为作为单个块解析的大量文本,并且 50,000 个字符串中的每一个都需要单独解析。

   try

     {

       let i, l, b, result, map, p;

       const c = 1000000;


       // First get the file map from front of blob/file.

       // Read first ten characters to get length of map JSON string.

       b = new Blob( [ f.slice(0,10) ], { type: 'text/csv' } ); 

       result = await read_file( b );

       l = parseInt(result.value);


       // Read the map string and parse to array of objects.

       b = new Blob( [ f.slice( 10, 10 + l) ], { type: 'text/csv' } ); 

       result = await read_file( b );

       map = JSON.parse(result.value); 


       l = map.length;

       p = 10 + result.value.length;


       // Using this loop taks about 7:30 to complete.

       for ( i = 1; i < l; i++ )

         {

           b = new Blob( [ f.slice( p, p + map[i].l ) ], { type: 'text/csv' } ); 

           result = await read_file( b ); // FileReader wrapped in a promise.

           result = await write_qst( JSON.parse( result.value ) ); // Database transaction wrapped in a promise.

           p = p + map[i].l;

           $("#msg").text( result );

         }; // next i


       $("#msg").text( "Successfully wrote all data to the database." );


       i = l = b = result = map = p = null;

     }

   catch(e)

     { 

       alert( "error " + e );

     }

   finally

     {

       f = null;

     }



/* 

  // Alternative loop that completes in about 1:30 versus 7:30 for above loop.


       for ( i = 1; i < l; i++ )

         { 

           let status = false, 

               k, j, n = 0, x = 0, 

               L = map[i].l,

               a_parse = [];



           if ( L < c ) status = true;

           while ( status )

             {

               if ( i+1 < l && L + map[i+1].l <= c ) 

                 {

                   L = L + map[i+1].l;

                   i = i + 1;

                   n = n + 1;

                 }

               else

                 {

                   status = false;

                 };

             }; // loop while


           b = new Blob( [ f.slice( p, p + L ) ], { type: 'text/csv' } ); 

           result = await read_file( b ); 

           j = i - n; 

           for ( k = j; k <= i; k++ )

             {

                a_parse.push( JSON.parse( result.value.substring( x, x + map[k].l ) ) );

                x = x + map[k].l;

             }; // next k

           result = await write_qst_grp( a_parse, i + ' of ' + l );

           p = p + L;

           $("#msg").text( result );

         }; // next i



*/



/*

// Was using this loop when thought the concern may be that the JSON strings were too large,
// but then realized the issue in my case is the opposite one of having 50,000 JSON strings of smaller size.

       for ( i = 1; i < l; i++ )

         {

           let x,

               m = map[i].l,

               str = [];

           while ( m > 0 )

             {

               x = Math.min( m, c );

               m = m - c;

               b = new Blob( [ f.slice( p, p + x ) ], { type: 'text/csv' } ); 

               result = await read_file( b );

               str.push( result.value );

               p = p + x;

             }; // loop while


            result = await write_qst( JSON.parse( str.join("") ) );

            $("#msg").text( result );

            str = null;

         }; // next i
*/           

有趣的是,您已经在问题中说过应该做什么:

切片你的斑点。

Blob 接口确实有一个.slice() method.
但要使用它,您应该跟踪合并发生的位置。 (可能位于数据库的其他字段中,甚至作为文件的标题:

function readChunks({blob, chunk_size}) {
  console.log('full Blob size', blob.size);
  const strings = [];  
  const reader = new FileReader();
  var cursor = 0;
  reader.onload = onsingleprocessed;
  
  readNext();
  
  function readNext() {
    // here is the magic
    const nextChunk = blob.slice(cursor, (cursor + chunk_size));
    cursor += chunk_size;
    reader.readAsText(nextChunk);
  }
  function onsingleprocessed() {
    strings.push(reader.result);
    if(cursor < blob.size) readNext();
    else {
      console.log('read %s chunks', strings.length);
      console.log('excerpt content of the first chunk',
        strings[0].substring(0, 30));
    }
  }
}



// we will do the demo in a Worker to not kill visitors page
function worker_script() {
  self.onmessage = e => {
    const blobs = [];
    const chunk_size = 1024*1024; // 1MB per chunk
    for(let i=0; i<500; i++) {
      let arr = new Uint8Array(chunk_size);
      arr.fill(97); // only 'a'
      blobs.push(new Blob([arr], {type:'text/plain'}));
    }
    const merged = new Blob(blobs, {type: 'text/plain'});
    self.postMessage({blob: merged, chunk_size: chunk_size});
  }
}
const worker_url = URL.createObjectURL(
  new Blob([`(${worker_script.toString()})()`],
    {type: 'application/javascript'}
  )
);
const worker = new Worker(worker_url);
worker.onmessage = e => readChunks(e.data);
worker.postMessage('do it');
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

从客户端读取文本文件并在客户端上超出了javascript中单个字符串的最大大小 的相关文章

随机推荐