3

I have following a tutorial in a book called "Sitepoint Full Stack Javascript with MEAN" and I've just finished chapter 6, and should've created a "server" with a "database". The database is nothing more than a JSON document. However, even though (what I can see), my code is a direct copy of his, I get the error mentioned in the title when i try to run it. It's var result = data.find(function(item) {... (line located in employees.js, about line 16) that is the cause of this problem. I can't see what else I can do, and hope you people can find a solution to my problem.

I have a couple of different files which I use for this.

Index.js:

var http = require('http');
var employeeService = require('./lib/employees');
var responder = require('./lib/responseGenerator');
var staticFile = responder.staticFile('/public');

http.createServer(function(req,res) {
    // a parsed url to work with in case there are parameters
    var _url;

    //In case the client uses lower case for methods
    req.method = req.method.toUpperCase();
    console.log(req.method + ' ' + req.url);

    if (req.method !== 'GET') {
        res.writeHead(501, {
            'Content-Type': 'text/plain'
        });
        return res.end(req.method + ' is not implemented by this server.');
    }

    if (_url = /^\/employees$/i.exec(req.url)) {
        //return a list of employess
        employeeService.getEmployees(function(error, data){
            if(error) {
                return responder.send500(error, res);
            }
            return responder.sendJson(data,res);
        });
    } else if (_url = /^\/employees\/(\d+)$/i.exec(req.url)){ 
        //find the employee by the id in the route
        employeeService.getEmployee(_url[1], function(error, data) {
            if (error) {
                return responder.send500(error, res);
            }
            if(!data) {
                return responder.send404(res);
            }
            return responder.sendJson(data,res);
        });

    } else{
            res.writeHead(200);
            res.end("static file")
    }


}).listen(1337);

console.log('server running');

employee.js

var employeeDb = require('../database/employees.json')

exports.getEmployees = getEmployees;
exports.getEmployee = getEmployee;

function getEmployees (callback) {
    setTimeout(function() {
        callback(null, employeeDb);
    }, 500);
}

function getEmployee (employeeId, callback) {
    getEmployees(function (error, data) {
        if (error) {
            return callback(error);
        }
        var result = data.find(function(item) {
            return item.id === employeeId;
        });
        callback(null, result)
    });
}

responseGenerator.js

var fs = require('fs');

exports.send404 = function (reponse) {
    console.error('Resource not found');
    response.writeHead(404, {
        'Content-Type': 'text/plain'
    });
    response.end('Not Found');
}

exports.sendJson = function(data, response) {
    response.writeHead(200, {
        'Content-Type': 'application/json'
    });

    response.end(JSON.stringify(data));
}

exports.send500 = function(data, response) {
    console.error(data.red);
    reponse.writeHead(500, {
        'Content-Type': 'text/plain'
    });
    response.end(data);
}

exports.staticFile = function(staticPath) {
    return function(data, response) {
        var readStream;

        // Fix so routes to /home and /home.html both work
        data = data.replace(/^(\/home)(.html)?$/i,'$1.html');
        data = '.' + staticPath + data;

        fs.stat(data, function(error, stats) {
            if (error || stats.isDirectory()) {
                return exports.send404(response);
            }

            readstream = fs.createReadStream(data);
            return readStream.pipe(response);
        });
    }
}

employees.json("database")

[
    {
        "id": "103",
        "name": {
            "first": "Colin",
            "last": "Ihrig"
        },
        "address": {
            "lines": ["11 Wall Street"],
            "city": "New York",
            "state": "NY",
            "zip": 10118
        }
    },
    {
        "id": "104",
        "name": {
            "first": "Idiot",
            "last": "Fjols"
        },
        "address": {
            "lines": ["Total taber"],
            "city": "Feeeee",
            "state": "Whatever",
            "zip": 10112
        }
    }


]

Hope you can help.

4
  • uhm.. employees.json doesn't have a find method. (it's an array, so that is expected.) If this code is copied directly from the book, i'm not sure what it's trying to teach you. Commented Mar 19, 2015 at 21:14
  • It looks like you may have intended to use .filter instead. Commented Mar 19, 2015 at 21:18
  • Yeah, .filter did the trick! Thank you. Commented Mar 20, 2015 at 7:41
  • You're just using an old version of node, try iojs instead. Array#find is a new method. Commented Apr 11, 2015 at 23:26

3 Answers 3

5

Page 80 of the book:

The find Method A quick note about the find method. It is in the spec for ECMAScript 6 but is currently unavailable in the Node runtime as of Node version 0.10.32. For this example, you can add a polyfill for the Array.find method. A polyfill is a term used to describe code that enables future JavaScript features in environments that are yet to support it. You can also write an additional method in lib/employees that locates an element in an array based on an ID. This bit of code will be removed once a true

If you donwloaded the book source code you can see waht the author did to make the find method available:

    Array.prototype.find = function (predicate) {
  for (var i = 0, value; i < this.length; i++) {
    value = this[i];
    if (predicate.call(this, value))
      return value;
  }
  return undefined;
}
Sign up to request clarification or add additional context in comments.

Comments

3

You can try using .filter method instead of .find method. Or change your array in database to json.

2 Comments

Thank you, .filter worked. Maybe it's an outdated book or something.
@Jacob to the contrary, it uses the new EcmaScript 6 API - developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/…
0

In index.js (the last else block) Em-Ant points out that:

The program as is will continue to respond with 'static file maybe' to every request not intercepted by the preceding routing tests.

https://github.com/spbooks/mean1/issues/3

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.