(JS)迭代后从csv中删除行

时间:2017-02-16 21:37:09

标签: javascript csv

我希望你能在每个脚本在该行上迭代后从csv文件中删除一行来帮助我吗?以下代码可以正常工作,迭代CSV并在每行基础上执行一个函数(选择将所有数据加载到数组中以提高速度),但我想删除顶部条目 - 一个刚刚使用过的 - 来自csv。目标是让跑步者能够连续调用任务,即使它崩溃了:

function change_yoast_page_titles($title)
{
  global $pagename;
  $new_title=$title;
  if ($pagename=='widget')
  {
    global $widget_name;
    if (isset($widget_name))
        $new_title=$widget_name." | ".get_bloginfo('name'); 
  }
  return $new_title;
}

add_filter('wpseo_title','change_yoast__page_titles',100);

1 个答案:

答案 0 :(得分:0)

使用Stream这样的东西应该可行。

const Transform = require('stream').Transform;
const util = require('util');
const Readable = require('stream').Readable;
const fs = require('fs');


class ProcessFirstLine extends Transform {
    constructor(args) {
        super(args);
        this._buff = '';
    }

    _transform(chunk, encoding, done) {

            // collect string into buffer
            this._buff += chunk.toString();

            // Create array of lines
            var arr = this._buff
                        .trim() // Remove empty lines at beginning and end of file
                        .split(/\n/), // Split lines into an array
                len = arr.length; // Get array length


            if(len > 0) {

                // Loop through array and process each line
                for(let i = 0; i < len; i++) {

                    // Grab first element from array
                    let line = arr.shift();

                    // Process the line
                    this.doSomethingWithLine(line);

                }

                // Push our array as a String (technically should be empty)
                this.push(arr.join(/\n/));

                // Empty the buffer
                this._buff = null;
            }

        done();
    }

    doSomethingWithLine(line) {
        console.log("doSomething:"+line);
    }
}

var input = fs.createReadStream('test.txt'); // read file
var output = fs.createWriteStream('test_.txt'); // write file

input
    .pipe(new ProcessFirstLine()) // pipe through line remover
    .pipe(output); // save to file
相关问题