Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/redis/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Node.js readline.createInterface({})中的变量。{}上的未更新_Node.js - Fatal编程技术网

Node.js readline.createInterface({})中的变量。{}上的未更新

Node.js readline.createInterface({})中的变量。{}上的未更新,node.js,Node.js,试图使用.csv文件中的值构造请求正文,但我的点数组未得到更新。我已经为on()函数内部和末尾的points数组执行了console.log(),这些值如预期的那样。但是我将console.log放在()上的之外,它表示数组为空 我知道这是一个范围问题,但对Node.js不太熟悉,所以无法理解。谢谢 // Detect anomalies in your spreadsheet var points = [] var dict = {} // Read the .csv file, conver

试图使用
.csv
文件中的值构造请求正文,但我的点数组未得到更新。我已经为
on()
函数内部和末尾的points数组执行了
console.log()
,这些值如预期的那样。但是我将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数组每次推送时都使用一个累积字典,而不是一个新字典。因此,在我可以再次查看上次打开()之外未更新的
点[]
之前,需要首先修复该问题

在当前代码中,我将API调用移动到最后一个
on()
函数中(以前它在函数之外,前面有一个
wait
):

更新2:

在答案中使用新代码时,出现新错误:
正文系列:未定义正文粒度:每小时
{错误:时间点应以每小时的粒度均匀分布,间隔为1 gran,缺失点的比率应小于10%,在2018-03-01 00:00:00和2018-04-16 00:00:00:00之间至少有994个点,但得到47个点。
这意味着什么

因为body对象看起来不错,所以打印时出现错误:

{ 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.' } }

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

问题是,在填充数组之前,您在错误的位置查看该数组。readline接口是异步的。因此,您可以调用
readline.createInterface()
并为
事件设置事件处理程序,然后代码继续运行。在readline操作完成之前,您将立即调用
异常检测客户端。entireDetect()

解决方案是等到readline接口读取完整个文件,并且直到
数组完全填充完毕,然后再尝试使用
数组

这里有一种方法,您可以在readline界面的
关闭
事件处理程序中处理
数组:

// 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);    
});

仅供参考,你真的确定你应该在响应中使用
项吗?
中的
不是用于数组,而是用于对象的属性。它对数组有一定的作用,但也不能工作很多次。
for/of
是专门为
for(let item of response.isanmaly){…}中的数组构建的对于一个数组,<代码> > <代码> >获取值的索引,而不是数组值。<代码> > />代码,得到您通常想要的数组值。

谢谢,这听起来是正确的。我通常不认为文件IO具有异步性,但这是有意义的。我将等待您的代码,谢谢!@ AuxRePOT-代码已添加。啊,谢谢,但它仍然返回为空。console.log()必须位于()上最后一个的外部。放在那里,它返回为空。我不能将API代码放在()上最后一个的内部
因为这样它就不允许我使用
wait
,我肯定必须在那里使用它,否则body的
系列:points
返回为null。除非我的API调用构造错误,或者其中有一个bug。@Azurespot-听起来你并不是在运行我给你看的代码。现在你说的是
a等待
在我的代码或您的问题中的代码中没有
等待
。因此,对不起,我无法回答有关新代码的问题。我看不出您编写的代码不在问题或我的答案中。我不知道那是什么。@Azurespot-很高兴让您了解这一点并进入下一期。
// 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);    
});