首页 > 解决方案 > 无法读取更新并保存到对象 csv 数据 typescript/js

问题描述

这是一个打字稿任何人都可以帮助以下内容:

  1. 我从 CSV 文件中读取数据
  2. 在飞行中转换此数据(删除一些额外的列)
  3. 然后我希望流中的更新 csv 返回代码中的变量。Console.log(updatedCsv) // 在流中 - 显示我需要的但是!当我尝试将它推入数组时,什么也没有发生,然后变量(我从流中推送数据)被认为是未定义的:

从“fs”导入*作为fs;从“csv”导入 * 作为 csv;

 udateCsv(){
        
        fs.createReadStream('allure-report/data/suites.csv')
        .pipe(csv.parse({ delimiter: ',', columns: true }))
        .pipe(csv.transform((input) => {
            console.log(input) // <----- it shows in console data I needed
            /* like this:
            {
                Status: 'passed',
                'Start Time': 'Wed Nov 11 17:37:33 EET 2020',
                'Stop Time': 'Wed Nov 11 17:37:33 EET 2020',
                'Duration in ms': '1',
                'Parent Suite': '',
                Suite: 'The Internet Guinea Pig Website: As a user, I can log into the secure area',
                'Sub Suite': '',
                'Test Class': 'The Internet Guinea Pig Website: As a user, I can log into the secure area',
                'Test Method': 'Hook',
                Name: 'Hook',
                Description: ''
                }

            */
            skipHeaders.forEach((header) => delete input[header]);
            this.rowsArray = input // NOTHING HAPPENS, rowsArray:  string[] = new Array(); input - I don't know what is the type or if I use push. I can't get this data out of pipe
            return input;
        }))
        .pipe(csv.stringify({ header: true }))
        .pipe(fs.createWriteStream( this.path))      

并且 作为一种解决方法,我想阅读新生成的 csv,但它也是不安全的,看起来我需要使用承诺。我尝试了一些来自互联网的示例,但失败了。请帮忙

标签: javascripttypescriptcsvparsing

解决方案


对于那些想知道的人 - 我能够使用以下方法解决我的目标: 但是!我仍然想知道如何通过 Promises、async/await 方法来处理这个问题。

class CsvFormatter{
    pathToNotUpdatedCsv: string
    readline: any
    readStream: any
    headers: any
    fieldSchema: string[] = new Array()
    rowsArray:  string[] = new Array()
    
    constructor(pathToCsv: string, encoding: string) {
        this.pathToNotUpdatedCsv = pathToCsv
        this.readStream = fs.createReadStream(this.pathToNotUpdatedCsv, encoding = 'utf8');      
     
    }
 async updateCsv(){
            //read all csv lines of not updated file
            this.readline = readline.createInterface({
                input: this.readStream,
                crlfDelay: Infinity
              });
            //save them to array
            for await (const line of this.readline) {
                this.rowsArray.push(line)
                
            }            
            //remove columns in csv and return updated csv array
            this.rowsArray = this.getUpdatedRows()
            //separating headers and other rows in csv
            this.headers = this.rowsArray.shift()
            
    }


    getUpdatedRows(){
        let headersBeforeUpdate = this.removeExtraQuotes(this.rowsArray[0])
        let rowsAfterUpdate = []
        let indexesOfColumnToDelete = []
        let partOfUpdatedArray = []        
        //get indexes which will be used for deletion of headers and content rows
        skipHeaders.forEach((header) => {           
             indexesOfColumnToDelete.push(headersBeforeUpdate.indexOf(header))
            })
        //delete rows by index 
        this.rowsArray.forEach(row => {   
            partOfUpdatedArray = this.removeExtraQuotes(row)
            indexesOfColumnToDelete.forEach(index=>{
                partOfUpdatedArray.splice(index)
                })
            rowsAfterUpdate.push(partOfUpdatedArray)
        })
            
            return rowsAfterUpdate
    }

推荐阅读