readline.createInterface({})。on({})中的变量未更新

时间:2019-08-15 03:38:42

标签: node.js

尝试使用.csv文件中的值构造一个请求正文,但是我的points数组没有更新。我已经完成了console.log()函数内部和结尾处的点数组的on(),并且值如预期的那样在那里。但是我在on()之外的console.log上说数组是空的。

我知道这是一个范围问题,但是对Node.js的了解并不多,所以无法弄清楚。谢谢。

// Detect anomalies in your spreadsheet
var points = []
var dict = {}
// Read the .csv file, convert date to Date object and number to float.
readline.createInterface({
    input: fs.createReadStream(CSV_FILE),
    terminal: false
}).on('line', function(line) {
    var row = line.split(",")
    dict[new Date(row[0])] = parseFloat(row[1])
    points.push(dict)
});

// Create request body for API call
let body = { series: points, granularity: 'hourly' }
// Make the call
anomalyDetectorClient.entireDetect(body)
    .then((response) => {
        for (item in response.isAnomaly) {
            if (item) {
                console.log("An anomaly was detected from the series.")
                console.log("Value: " + response.expectedValues[response.indexOf(item)])
            } 
        }
    }).catch((error) => {
        console.log(error)
    }) 

更新:

我正在尝试将异步函数移至on()中,因此points[]中包含值...但是请求中包含错误的正文,我的points数组占用了每次推送时都使用累积字典,而不是新字典。因此需要首先解决这一问题,然后才能在最后一个on()之外再次查看未更新的points[]

当前代码,我将API调用移到了最后一个on()函数中(以前是在它外部,前面是await):

async function main() {
    let CSV_FILE = './request-data.csv'

    // Detect anomalies in your spreadsheet
    var points = []

    // Read the .csv file
    await readline.createInterface({
        input: fs.createReadStream(CSV_FILE),
        terminal: false
    }).on('line', function(line) {
        var row = line.split(",")
        // Convert date to Date object and number to float.
        var date = new Date(row[0])
        var dict = {}
        dict[date] = parseFloat(row[1])
        points.push(dict)
        console.log(points)
    }).on('close', function() {
         // Create request body for API call
        let body = { series: points, granularity: 'hourly' }

        console.log("Body series: " + body.series.timestamp + "Body granularity: " + body.granularity)
        // Make the call
        anomalyDetectorClient.entireDetect(body)
            .then((response) => {
                for (item in response.isAnomaly) {
                    if (item) {
                        console.log("An anomaly was detected from the series.")
                        console.log("Value: " + response.expectedValues[response.indexOf(item)])
                    } 
                }
            }).catch((error) => {
                console.log(error)
            })  
    })

更新2:

在答案中使用新代码,出现一个新错误: Body series: undefinedBody granularity: hourly { Error: Time points should be uniformly spaced in time in hourly granularity with 1 gran as interval, ratio of missing points should be less than 10%, between 2018-03-01 00:00:00 and 2018-04-16 00:00:00 there should be at least 994 points, but got 47 points.是什么意思?

由于主体对象看起来不错而感到困惑,它的打印错误如下:

{ Error: Time points should be uniformly spaced in time in hourly granularity with 1 gran as interval, ratio of missing points should be less than 10%, between 2018-03-01 00:00:00 and 2018-04-16 00:00:00 there should be at least 994 points, but got 47 points.
    at new RestError (C:\Users\v-wiazur\Desktop\Anomaly Detector\node_modules\@azure\ms-rest-js\dist\msRest.node.js:1399:28)
    at C:\Users\v-wiazur\Desktop\Anomaly Detector\node_modules\@azure\ms-rest-js\dist\msRest.node.js:2494:37
    at process._tickCallback (internal/process/next_tick.js:68:7)
  code: 'InvalidSeries',
  statusCode: 400,
  request:
   WebResource {
     streamResponseBody: false,
     url:
      'https://winonaanomalydetector.cognitiveservices.azure.com/anomalydetector/v1.0/timeseries/entire/detect',
     method: 'POST',
     headers: HttpHeaders { _headersMap: [Object] },
     body:
      '{"series":[{"timestamp":"2018-03-01T00:00:00.000Z","value":32858923},{"timestamp":"2018-03-02T00:00:00.000Z","value":29615278},{"timestamp":"2018-03-03T00:00:00.000Z","value":22839355},{"timestamp":"2018-03-04T00:00:00.000Z","value":25948736},{"timestamp":"2018-03-05T00:00:00.000Z","value":34139159},{"timestamp":"2018-03-06T00:00:00.000Z","value":33843985},{"timestamp":"2018-03-07T00:00:00.000Z","value":33637661},{"timestamp":"2018-03-08T00:00:00.000Z","value":32627350},{"timestamp":"2018-03-09T00:00:00.000Z","value":29881076},{"timestamp":"2018-03-10T00:00:00.000Z","value":22681575},{"timestamp":"2018-03-11T00:00:00.000Z","value":24629393},{"timestamp":"2018-03-12T00:00:00.000Z","value":34010679},{"timestamp":"2018-03-13T00:00:00.000Z","value":33893888},{"timestamp":"2018-03-14T00:00:00.000Z","value":33760076},{"timestamp":"2018-03-15T00:00:00.000Z","value":33093515},{"timestamp":"2018-03-16T00:00:00.000Z","value":29945555},{"timestamp":"2018-03-17T00:00:00.000Z","value":22676212},{"timestamp":"2018-03-18T00:00:00.000Z","value":25262514},{"timestamp":"2018-03-19T00:00:00.000Z","value":33631649},{"timestamp":"2018-03-20T00:00:00.000Z","value":34468310},{"timestamp":"2018-03-21T00:00:00.000Z","value":34212281},{"timestamp":"2018-03-22T00:00:00.000Z","value":38144434},{"timestamp":"2018-03-23T00:00:00.000Z","value":34662949},{"timestamp":"2018-03-24T00:00:00.000Z","value":24623684},{"timestamp":"2018-03-25T00:00:00.000Z","value":26530491},{"timestamp":"2018-03-26T00:00:00.000Z","value":35445003},{"timestamp":"2018-03-27T00:00:00.000Z","value":34250789},{"timestamp":"2018-03-28T00:00:00.000Z","value":33423012},{"timestamp":"2018-03-29T00:00:00.000Z","value":30744783},{"timestamp":"2018-03-30T00:00:00.000Z","value":25825128},{"timestamp":"2018-03-31T00:00:00.000Z","value":21244209},{"timestamp":"2018-04-01T00:00:00.000Z","value":22576956},{"timestamp":"2018-04-02T00:00:00.000Z","value":31957221},{"timestamp":"2018-04-03T00:00:00.000Z","value":33841228},{"timestamp":"2018-04-04T00:00:00.000Z","value":33554483},{"timestamp":"2018-04-05T00:00:00.000Z","value":32383350},{"timestamp":"2018-04-06T00:00:00.000Z","value":29494850},{"timestamp":"2018-04-07T00:00:00.000Z","value":22815534},{"timestamp":"2018-04-08T00:00:00.000Z","value":25557267},{"timestamp":"2018-04-09T00:00:00.000Z","value":34858252},{"timestamp":"2018-04-10T00:00:00.000Z","value":34750597},{"timestamp":"2018-04-11T00:00:00.000Z","value":34717956},{"timestamp":"2018-04-12T00:00:00.000Z","value":34132534},{"timestamp":"2018-04-13T00:00:00.000Z","value":30762236},{"timestamp":"2018-04-14T00:00:00.000Z","value":22504059},{"timestamp":"2018-04-15T00:00:00.000Z","value":26149060},{"timestamp":"2018-04-16T00:00:00.000Z","value":35250105}],"granularity":"hourly"}',
     query: undefined,
     formData: undefined,
     withCredentials: false,
     abortSignal: undefined,
     timeout: 0,
     onUploadProgress: undefined,
     onDownloadProgress: undefined,
     proxySettings: undefined,
     operationSpec:
      { httpMethod: 'POST',
        path: 'timeseries/entire/detect',
        urlParameters: [Array],
        requestBody: [Object],
        responses: [Object],
        serializer: [Serializer] } },
  response:
   { body:
      '{"code":"InvalidSeries","message":"Time points should be uniformly spaced in time in hourly granularity with 1 gran as interval, ratio of missing points should be less than 10%, between 2018-03-01 00:00:00 and 2018-04-16 00:00:00 there should be at least 994 points, but got 47 points."}\n',
     headers: HttpHeaders { _headersMap: [Object] },
     status: 400 },
  body:
   { code: 'InvalidSeries',
     message:
      'Time points should be uniformly spaced in time in hourly granularity with 1 gran as interval, ratio of missing points should be less than 10%, between 2018-03-01 00:00:00 and 2018-04-16 00:00:00 there should be at least 994 points, but got 47 points.' } }

1 个答案:

答案 0 :(得分:1)

您的数组正在更新。如果您在console.log(points)事件处理程序中执行line,则每次都会看到它累积日期。

问题是您在填充阵列之前在错误的位置查看了阵列。 readline接口是异步的。因此,您调用readline.createInterface()并为line事件设置事件处理程序,然后代码将继续运行。您将在readline操作完成之前立即调用anomalyDetectorClient.entireDetect()

解决方案是等待尝试使用points数组之前,直到readline界面读取完整个文件,并完全填充points数组为止。

这是一种方法,您可以在points事件处理程序中为readline接口处理close数组:

// Detect anomalies in your spreadsheet
var points = [];
var dict = {};
// Read the .csv file, convert date to Date object and number to float.
readline.createInterface({
    input: fs.createReadStream(CSV_FILE),
    terminal: false
}).on('line', function(line) {
    var row = line.split(",");
    let point = {
        timestamp: new Date(row[0]), 
        value: parseFloat(row[1])
    };
    dict[point.date] = point.value;
    points.push(point);
    console.log(points);
}).on('close', function() {
    // now we're done reading the file
    console.log(points);   // all the points are here

    // now process the points
    // Create request body for API call
    let body = { series: points, granularity: 'hourly' };
    // Make the call
    anomalyDetectorClient.entireDetect(body).then((response) => {
        for (let item in response.isAnomaly) {
            if (item) {
                console.log("An anomaly was detected from the series.")
                console.log("Value: " + response.expectedValues[response.indexOf(item)])
            }
        }
    }).catch((error) => {
        console.log(error)
    });

}).on('error', function(err) {
    // handle errors here
    console.log(err);    
});

仅供参考,您确定要使用item in response.isAnomaly吗? in不是用于数组,而是用于对象的属性。它有点儿适用于数组,但也不能多次工作。 for/offor (let item of response.isAnomaly) {...}中一样,是专门为数组构建的。另外,对于数组,in会为您提供值的索引,而不是数组值。 of为您提供通常所需的数组值。