Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to solve TypeError: d3.time is undefined?

I want to parse data/time using D3.js. For that purpose I created one javascript file and use var d3 = require('d3'). I install D3 using npm install d3, and also tried npm install d3 --save which saves it in package.json file :

{
  "name": "school",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "author": "",
  "license": "ISC",
  "dependencies": {
    "browserify": "^13.1.0",
    "bufferutil": "^1.2.1",
    "d3": "^4.2.2",
    "express": "^4.14.0",
    "guid": "0.0.12",
    "gulp": "^3.9.1",
    "react": "^15.3.1",
    "react-dom": "^15.3.1",
    "reactify": "^1.1.1",
    "utf-8-validate": "^1.2.1",
    "vinyl-source-stream": "^1.1.0",
    "websocket": "^1.0.23",
    "ws": "^1.1.1"
  }
}

However, I'm facing this exception:

TypeError: d3.time is undefined

program code:

'use strict';

var d3 = require("d3");
var latency_arr = [];
var time_arr = [];
var timeFormat = d3.time.format('%H:%M:%S %L');

module.exports = {
  histogram: function(data) {
    console.log(data);
    return {

      getBin: function() {

        var jsonObject = JSON.parse(data);
        this.time_arr = jsonObject.time;
        for(var i = 0 ; i < this.time_arr.length ; i++){
            temp_time = this.time_arr[i];
            this.time_arr[i] = new Date(timeFormat.parse(temp_time));
        }
        return this.time_arr;
      },

      addValue: function(date, value) {
        return true;
      },

      getValues: function() {
        if(data !== undefined){
            var jsonObject = JSON.parse(data);
            this.latency_arr = jsonObject.latency;
            return this.latency_arr;
        }
      }
    };
  }
};

Checking :

> var d3 = require('d3');
undefined

But the d3 module is in node_modules directory.

Why didn't it recognize the d3 module? What am I missing?

like image 245
ketan Avatar asked Sep 07 '16 12:09

ketan


1 Answers

You are requiring D3 v4.2.2 that doesn't have a d3.time property any more, which was part of D3 v3. According to the changelog the time formats have been subject to the general namespace flattening and were therefore renamed as follows:

  • d3.time.format ↦ d3.timeFormat
  • d3.time.format.utc ↦ d3.utcFormat
  • d3.time.format.iso ↦ d3.isoFormat

That said, it does recognize the d3 object, wheras the d3.time is undefined. Changing your code to

var timeFormat = d3.timeFormat('%H:%M:%S %L');

should do the trick.

like image 137
altocumulus Avatar answered Nov 15 '22 09:11

altocumulus