Faigjaz Faigjaz - 1 year ago 86
Node.js Question

node.js - get method with ID

I've got a node.js server receiving data from a user.json file

var express = require("express");
var app = express();
var bodyParser = require("body-parser");
var router = express.Router();
var cors = require('cors')
var fs = require("fs");
app.use(bodyParser.urlencoded({"extended" : false}));

app.get('/listUsers', function (req, res) {
fs.readFile( __dirname + "/" + "users.json", 'utf8', function (err, data) {
//console.log( data );

res.end( data );

var server = app.listen(8081, function () {

var host = server.address().address
var port = server.address().port

console.log("Example app listening at http://%s:%s", host, port)



{ "data": [
"name" : "mahesh",
"password" : "password1",
"profession" : "teacher",
"id": 1
"name" : "suresh",
"password" : "password2",
"profession" : "librarian",
"id": 2
"name" : "ramesh",
"password" : "password3",
"profession" : "clerk",
"id": 3

As you see, the get request displays all of the users on the route /listUsers.
Now I want to get them by ID do delete a specific user.

URL should look like this: /listUsers/id

But as I'm very new to this, I acutally don't know how to do it.

My thoughts are, that I first need to read the whole file and then somehow set the ID into the url.
But how can I do this?
Isn't the request send BEFORE executing the function?
So when I do sth like this:

app.get('/listUsers/{this.id}'. function(req,res){
fs.readFile(_dirname + "/" + "users.json", "utf8", function(err, data) {
res.end( data )
id = this.data.id

It won't work.
I actually don't want to use a mongoDB or something, I want this to work with only the nodejs server for testing purposes, IF possible.
Any thought/suggestions?

Answer Source

The app.get method has a trick for you. The route string might contain parameters prefixed with a colon. These are put into the req.params object.

var _ = require('lodash');

app.get('/user/:id', function(req, res) {
  fs.readFile(_dirname + "/" + "users.json", "utf8", function(err, data) {
    var allUsers = JSON.parse(data).data;
    res.end( JSON.stringify(_.find(allUsers, function(o) { return o.id == req.params.id })) )

I used lodash to simplify searching the given user in the users.json file.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download