2

I am going to learn Node.js and right now I was trying to make a small demo project which implements an HTTP REST service. My idea is to divide the APIs (url) by Resources and end up in a structure like the following one:

- user
 > index.js
 > post.js
 > put.js
 > delete.js
 > functions.js
- person
 > index.js
- index.js

So, if you are familiar with ASP.NET Web Api, I am trying to make every module of Node.js a Controller and every web method a single file (.js), in order to have an high maintainability in the future.

Question Right now, my index.js file return the following:

var http = require('http');
var server = http.createServer();

How can I configure a specific "Request Handler" in each file by using this module? At the moment the createServer() method return a server object can use a single server.on('request', function) while I need to handle each request in a different file.

4
  • 2
    What you could do is use express.js, create the server in your main file, and have post, put... returns Router object that you can attach to the server. Commented Aug 16, 2016 at 8:44
  • 1
    You need to check the request method and parse the url to build a handler module name. Another possible solution to manually configure the application, but that would be non-DRY. Commented Aug 16, 2016 at 8:45
  • 1
    Thank you guys, then I will start to have a look at expressjs.com, and move forward from there. Commented Aug 16, 2016 at 8:54
  • Possible duplicate of Bigger projects Node.js and RESTful API Commented Aug 16, 2016 at 9:12

1 Answer 1

2

Go ahead learning with the help of some framework. They provide scaffolding of project.

If you are developing a complete web app(MVC) then go for ExpressJs or SailsJs

If you are looking out to develop only API(No Views) then go for Strongloop or Restify

There are many more frameworks but the above ones are popular.

Sign up to request clarification or add additional context in comments.

2 Comments

Thanks, no I am implementing only Api for now but at this point I will consider express.
Just to keep the audience "updated" on my progresses, I spent now over a week on Express + Knex (Database) and + Bookshelf (ORM) and I have made a barely basic REST API project. I would suggest to others to learn Express and Bookshelf, they can make life a lot easier and they "resemble" the .NET syntax/project structure

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.