如何使用 node-mysql 而不将所有行加载到内存中?

How to use node-mysql without loads all the rows into the memory?

我正在使用 NodeJS。我想对 1,000,000 行执行某些操作而不将所有行加载到内存中。 (每个)

以前,当我使用 ASP Classic 时,我做了:

do while not rec.eof
   //do something
   rec.movenext
loop

在 node-mysql 中我没有发现任何与光标相似的东西。只有

connection.query('select * from bigdata',function(err,rows))

问题是,我不想一次加载所有行。

I found an answer, and put it below. I keep the question to help others who will have the same question

connection.query('select * from bigdata',function(err,rows){
    rows.foreach(function(){
        console.log(this);
    });
});

感谢Ziggy Jonshon,我在node-mysql中发现了类似于游标的东西,使用stream。

我可以通过流获取查询结果,并自动暂停:

See Issue #1370 on node-mysql:

const mysql = require('mysql');
const stream = require('stream');

connection.query('SELECT * FROM `bigdata`')
  .on('error', function(err) {
    // Do something about error in the query
  })
  .stream()
  .pipe(new stream.Transform({
    objectMode: true,
    transform: function (row, encoding, callback) {
      // Do something with the row of data

      callback();
    }
  }))
  .on('finish', function() {
    connection.end();
  });

这样我就不需要把所有的数据都加载到节点进程的内存中了。