Git Product home page Git Product logo

diet's Introduction

Diet Logo

Build Status NPM Downloads Coveralls

Diet is a tiny, fast and modular node.js web framework. Good for making fast & scalable apps and apis.

var server = require('diet')

var app = server()
app.listen(8000)
app.get('/', function($){
    $.end('hello world')
})

Features

Install

npm install diet

Website & Community

Tutorials

API

Resources

License

(The MIT License)

Copyright (c) 2014 Halász Ádám

Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

diet's People

Contributors

adamhalasz avatar barenko avatar demarius avatar floatdrop avatar frank-dspeed avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

diet's Issues

Suggestion: rename signal properties for better readability on request and response

I am sure it happens on many developers (specially when they are trying for the first time this framework) that some signal properties have the same name for request and response.. i would suggest to change the names of these properties like this

For Request:
$.header() => $.getHeader()
$.headers() => $.getHeaders()

for Response:
$.header() => $.setHeader()     //Specially this property cause it's also available for request
$.headers() => $.setHeaders()  //I thought on this one to just pass an object as parameter

Parsing .listen values right

first check if '://' exist if '://'
if exist we got protocoll else we suggest http and do url.parse the listen value

then we got a listen_url_obj.hostname
listen_url_obj.port if port is empty we suggest 80!

if we listen only on port we need to care for that case with extra thinking because it brakes the server host:port array

maybe its my first suggestion never listen on 80 directly and error! or we default localhost as we do but when we default localhost we need to alert and error if localhost:80 is set to a other app because else the secund overwrites the first localhost:80 via server.js create server!

Semantic-ui and RekordJs Support or Module?

I'm not that great at coding, but I was thinking of using the three together. I'm going to try and hopefully hack something together, but it would be nice if there was some sort of official support to help start me off.
~Thanks!

Diet + OpenShift

Trying to get a simple Diet server running on OpenShift (free plan) but the server never starts (runs fine locally). The page itself (http://diet-levelout.rhcloud.com/) returns a 503 and the logs throw:

http://dietjs.com/
 ... HTTP Server is listening on http://127.5.35.1:8080
{ protocol: 'http:',
  slashes: true,
  auth: null,
  host: '10.225.25.124:8080',
  port: '8080',
  hostname: '10.225.25.124',
  hash: null,
  search: null,
  query: null,
  pathname: '/',
  path: '/',
  href: 'http://10.225.25.124:8080/' }
events.js:72
    throw er; // Unhandled 'error' event
              ^
Error: listen EACCES
    at errnoException (net.js:901:11)
    at Server._listen2 (net.js:1020:19)
    at listen (net.js:1061:10)
    at Server.listen (net.js:1135:5)
    at App.listen (/var/lib/openshift/558a6ec9e0b8cd5c870000e2/app-root/runtime/repo/node_modules/diet/models/server.js:19:35)
    at Object.<anonymous> (/var/lib/openshift/558a6ec9e0b8cd5c870000e2/app-root/runtime/repo/server.js:8:5)
    at Module._compile (module.js:456:26)
    at Object.Module._extensions..js (module.js:474:10)
    at Module.load (module.js:356:32)
    at Function.Module._load (module.js:312:12)
DEBUG: Program node server.js exited with code 8

Here's the code:

var server = require('diet'),
    app = server();

var server_ip_address = process.env.OPENSHIFT_NODEJS_IP || '127.0.0.1';
var server_port = process.env.OPENSHIFT_NODEJS_PORT || 3000;

app.listen('http://' + server_ip_address + ':' + server_port);

console.log(app.location);

app.get('/', function ($) {
  $.end('Hello World!');
});

The server runs with the default example and a simple Express 🙉 app but not the above.

Any ideas?

HTTP methods

Supporting other HTTP methods like PUT, DELETE and PATCH

Couldn't listen to DietJs at Cloud9 service.

There's a problem that I can't listen to port 80 at c9 cloud service, so there's a proxy redirecting all my requests at port 80 and should be redirecting them to port 8080 which is the default port of c9.

For that reason I cant listen to dietjs framework at c9.io.

PR: Add Method for unregister routes and servers

We should add 2 new Methods

One Removes Listen (http servers)
One Removes routes all kinds of head, foot, missing, get

This will enable us to Dynamicaly Register Domains and Routes for them

we can overwrite the app.servers object for that so this is solved
we can overwrite and parse the registered routes in the app router

Question: How can I disable listening on port 80?

Hi,

I my aim is to have multiple diet instances but spread across different files. For Example:
File 1

var server = require('diet');

var app = server();
app.listen("mydomain.co.uk");

app.get('/', function($){
  $.end('Hello World');
});

File 2

var server = require('diet');

var app = server();
app.listen("myseconddomain.co.uk");

app.get('/', function($){
  $.end('Hello World 2');
});

When I start the first file it works OK but when starting the other it errors:

Error: listen EADDRINUSE 0.0.0.0:80
    at Object.exports._errnoException (util.js:1008:11)
    at exports._exceptionWithHostPort (util.js:1031:20)
    at Server._listen2 (net.js:1253:14)
    at listen (net.js:1289:10)
    at net.js:1399:9
    at _combinedTickCallback (internal/process/next_tick.js:77:11)
    at process._tickDomainCallback (internal/process/next_tick.js:122:9)
    at Module.runMain (module.js:577:11)
    at run (bootstrap_node.js:352:7)
    at startup (bootstrap_node.js:144:9)

and when I go to my VPS IP it says 404 host not found. So I'm guessing its not working because both files are trying to listen on port 80 to show 404 host not found.

Please someone help.

Thanks in advance.

Is this still maintained?

This framework is really great but the website says the current version is 0.9 while here it is 0.10, the last commit and issues are like 4 months old..

So I wonder if this framework is still maintained

Configuring other templating engines

I just tried to use the Nunjucks templating engine

var nunjucks = require('nunjucks');

    nunjucks.configure(app.path+'/views/nunjucks/', {
        autoescape: true,
        express: app,
        watch: true
    });
    app.view('html', nunjucks.render);

This does not work as expected, here is the error I received

/home/kokujin/development/research/diet_test/node_modules/nunjucks/src/environment.js:287
        app.set('view', NunjucksView);
            ^

TypeError: app.set is not a function
  at Obj.extend.express (/home/kokujin/development/research/diet_test/node_modules/nunjucks/src/environment.js:287:13)
  at Object.module.exports.configure (/home/kokujin/development/research/diet_test/node_modules/nunjucks/index.js:54:11)
  at Object.<anonymous> (/home/kokujin/development/research/diet_test/index.js:33:14)
  at Module._compile (module.js:541:32)
  at Object.Module._extensions..js (module.js:550:10)
  at Module.load (module.js:458:32)
  at tryModuleLoad (module.js:417:12)
  at Function.Module._load (module.js:409:3)
  at Function.Module.runMain (module.js:575:10)
  at startup (node.js:160:18)
  at node.js:449:3

What should I look out for or what other steps should I take to properly configure other engines?

Thanks

What is the future of this?

I really like this framework and want to use it for production after using it in some internal projects, is this gonna be maintained or it is just a hobby project?

Bug with the host controller

It seems there is a bug with the host controller. I think the problem comes when the request method is not GET or POST. Search engines sometimes use different http methods.

Proposal: Make Diet Flexible

We should de couple all parts of DietJS that are at present bound to the listen function.

we should export a method that creates the server
and should export a method that creates the Host so that

http.createServer(diet.hosts['app in this array']).listen(9011);

maybe rename diet.hosts that get matched to diet apps so that it gets clear that this are complet diet.apps

so that we can create apps for hostmatches in

diet = require diet // returns server and app part but app part
server = diet.server() // init diet server object


// allwo to give app as options and if not given a diet.app() instance we simply init one and return that as app to that host
server.listen({ location: '', app1})

app1 = diet.app() // returns only app relevant parts not the server parts
app2 = diet.app() // returns only app relevant parts not the server parts

if app not present simply use diet (this)

this will then allow more clear app seperation and less confusing when listing with more then one diet instance.

some people even dont understand that diet = require diet is a object thats not allowed to be re instanced if you make many apps it only works with seperated files because nodejs returns same object for already required objects.

Nginx doesn't work with Diet?

I have a Diet.js API running on http://127.0.0.1:6000, and I'm trying to set up nginx to proxy requests to the API. But it doesn't work - nginx invariably throws up a 404 host not found error.

I saw this issue, and it seems similar to the predicament I'm in. Unfortunately, I can't figure out where to apply the same fix, because I suppose models/host.js was deprecated or something. How can I get this to work?

Thanks!

EDIT - I've also tried running the API on 0.0.0.0, but the same problem persists.

JSON bodies

I can't seem to accept a properly parsed JSON body in a POST request:

Sending a request with Content-Type: application/json in the header and

{
    "hello": "world"
}

I would expect to be able to access this through $.body.hello but it seems to be parsed incorrectly with output like this:

{ '\'hello\': \'world\'': 'undefined' }

Is this something that will require middleware?

Load test

On this page it's said that

Diet is significantly faster than Vanilla Node.js.

I've created a simple benchmark whose results you can see here. Diet seems slower than Express in my tests.
Is there something I'm missing?
I've also tried setting NODE_ENV to production but it didn't make any difference.

Support for mounting diet as middleware layer.

This will Add cross compatiblity to diet.js

Allow: use in express diet.js middelware.
Allow: use httpCreate server with diet.js
Allow: use of express middelware in dietjs without converting via converting signal to req, res and vice versa with perserving Options!

build and return a function called diet.mount(req, res, next)
This will allow mounting dietjs as a middleware routing layer of express, connect, httpServer

We will offer a extra mount point that can be used in express, connect, httpServer.create()

that takes req, res, next only forms signal

this will allow:
app = require('express')
diet = require('diet')

diet.get('/', function($){
console.log('1st route', '1st middleware')
$.end('hello world!', true); // <-- stop middleware chain
}, function(){
console.log('1st route', '2nd middleware')
})

diet.get('/', function(){
console.log('2nd route', '1st middleware')
})

// diet.mount convert req, res, next to signal that used req, res, next
app.use(diet.mount(options))

Add socket io example to homepage

// Diet Server
var server = require('diet')
var app = server()
app.listen(8000)

// Socket.io
var io = require('socket.io')(app.server) // <-- use app.server 

// Listen on websocket connection
io.on('connection', function(socket){
  console.log('a user connected');
});

// Now you can access socket.io from client side with:
// http://localhost:8000/socket.io/socket.io.js

Add grouping route

Could be a nice idea.. but what if there was a function that groups all methods in a single route?

for example:

app.group('/books', function(method){
    method.get(function($){

    });

    method.post(function($){

    });

    method.put(function($){

    });

    method.delete(function($){

    });

    // Other methods too..
});

hi, how to compressing resources ( gzip ) with dietjs?

*Actually this is not a issue.
Hi, dietjs is one of the best web framework of nodejs, and I have a web project up and running which use dietjs and nedb, everything working great as expected.
However, PageSpeed Insights asked me to compressing resources to reduce their transfer size. I googled around and was unable to find any sample or hint about dietjs and gzip/zlib ( everyone just talking about expressjs), I have no idea how to respond the gunzip. Can you kindly give us a sample? Thanks!

app.missing() not working

Diet version: 0.10.7

app.missing() is not working when there is no uri that matches with the request

Redirect all routes to reactjs/react-router with static files

I need to redirect all routes to reactjs/react-router. diet-static must work and custom routes too.

const fs = require("fs")
const url = require("url")
const path = require("path")

const diet = require("diet")

const server = diet()

server.listen("http://www.google.sk")

const experiment = require("diet-static")({
  path: server.path + "/public"
})

server.footer(experiment);

server.get("/", ($) => {
  let a = path.join(server.path, "public", "index.html")

  fs.readFile(a, (error, data) => {
    $.header("Content-Type", "text/html")
    $.send(data)
    $.end()
  })
})

server.get("*", ($) => {}) does not work with diet-static

Wrong ip Detected inside Containers

listen('http://address.tld') fails inside linux namespace and lxc containers it gets the ip reversing to the hostname address.tld but it dont needs to run on same ip as the domain points too. So this needs removement for Production use cases where domain reverse dns ip is not the same as app ip

listen on ip first and then on the hosts fixes this but i think in general this needs fixing.

Goal is. Running adiet.js ap with only listen('http://bla.com')

suggestion to archiv this is to simply listen on all ips by default and not localhost
you probally setted localhost for your own testing.
if nothing is binded and we whant to bind a domain string then we need to bind to 0.0.0.0 first so all devices not only 127.0.0.1

events.js:160
throw er; // Unhandled 'error' event
^

Error: listen EADDRNOTAVAIL 5.x.x.x:80
at Object.exports._errnoException (util.js:896:11)
at exports._exceptionWithHostPort (util.js:919:20)
at Server._listen2 (net.js:1233:19)
at listen (net.js:1282:10)
at net.js:1392:9
at GetAddrInfoReqWrap.asyncCallback as callback
at GetAddrInfoReqWrap.onlookup as oncomplete
root@40fe87196f3c:/app#

PR: Decouple Listen host and app

for people that whant to run a single instance with support for lets say 5000+ domains its usefull to de couple the app name and from listen

at present listen creats a new object for every domain

better would be to listen simply on a port and then do a array for domain.tld = appname

greetings

ps. it would only need smal modification of hosts.js and index.js so we add a option for the object/array that stores domain to app routing.

Can I listen on mydomain.com and also www.mydomain.com without making 2 servers?

Hi,

I have multiple websites hosted with Diet and I have realized only recently I can only access it using mydomain.com and not www.mydomain.com.

Here is some example code of my site currently.

var server = require('diet')
var app = server()
app.listen('http://mydomain.com/')

app.get('/', function($){
  $.end('Hello World!')
});

It only listens on mydomain.com not www.mydomain.com.

How can I get it do do this without doing (preferably):

var server = require('diet')
var app = server()
var app1 = server()
app.listen('http://mydomain.com/')
app1.listen('http://www.mydomain.com/')

app.get('/', function($){
  $.end('Hello World!')
});

app1.get('/', function($){
  $.end('Hello World!')
});

Thanks in advance.

New Test Cases Needed!

Following looks none working.

Creating domains in a other app that listen on same port as the app befor

so we need following test to pass befor any thing gets done

app1 = server();
app1 = listen(80)
app1 = routes header or else
app1 = listen('testhost.com')
app1 = listen('host2.tld:80')
app1.listen('http://host3.tld')

app2.listen(80)
app2.header()
app2.listen('http://bla.com:80')

app3.listen('last.com')
app3.footer('any')
app3 = server();

app.put() body is not parsed

running on Diet 0.10.8, just making the First PUT i have ever done on a server and i have found out that $.body on this method is not being parsed, the whole data is still serialized

app.routes overwrite by listen

if you call listen after a app route already is pushed it will set empty routes via server.js

so app.listen() clears all existing routes!

404 host not found in public server

just exact what the title says.. i can access it by localhost.. but host cant be accessed through public ip.. even when ports are open for public..

Add server properties in documentation

i have seen in diet-static example that uses path to get the directory of the application.. but i don't see this kind of information in the documentation..

there should be a section that shows all the properties available in diet server

Update github releases and tags

This Project falls behind consistent state if we don't update the tags and releases of this repository. i would offer also my self to get added to this project as extra maintainer for faster reaction. as i use this code base in production.

Also a git repo for the framework homepage probally would be good the gh-pages branch don't looks like the current page this is also considered inconsistent.

PLZ: Release Current Version 1.0

It would be nice if you find time to release this as version 1.0 also publish npm and also make a git tag for that version thx a lot for corperation.

Proposal: TCP Port Multiplexing!

Implament code support for this clib
https://github.com/direktspeed/sslh

it will ENABLE us to make more then one DIETJS application bind to the same TCP port!!!

sslh accepts connections on specified ports, and forwards them further based on tests performed on the first data packet sent by the remote client.

Probes for HTTP, SSL, SSH, OpenVPN, tinc, XMPP are implemented, and any other protocol that can be tested using a regular expression, can be recognised. A typical use case is to allow serving several services on port 443 (e.g. to connect to ssh from inside a corporate firewall, which almost never block port 443) while still serving HTTPS on that port.

Hence sslh acts as a protocol demultiplexer, or a switchboard. Its name comes from its original function to serve SSH and HTTPS on the same port.

sslh supports IPv6, privilege dropping, transparent proxying, and more.

REQUEST: $.multipart always set to false

Making test with this simple html

<!DOCTYPE html>
<html>
<head>
    <title>test</title>
    <meta charset="utf-8">
</head>
<body>
    <form action="http://127.0.0.1:3000" method="post" enctype="multipart/form-data">
        <input type="text" name="imageName">
        <input type="file" name="sam">
        <input type="submit" name="send">
    </form>
</body>
</html>

And logging in diet server, i see that multipart is set to false, and also.. $.body is undefined

i found this while i was struggling to see why the server was never getting the file from one of my projects.. this could be a bug or i am missing something

the testing server has this code

var diet = require("diet");

var app = diet();

app.listen(3000);

app.header(function($){
    console.log({
        url: $.url,
        method: $.method,
        body: $.body,
        multipart: $.multipart
    });

    $.header('Access-Control-Allow-Origin', '*');
    $.header('Access-Control-Allow-Headers', 'Content-Type');
    $.header('Access-Control-Allow-Methods', 'GET, POST, OPTIONS, PUT, DELETE');
    $.header('Access-Control-Allow-Credentials', true);


    $.end();
});

API middleware with token authentication except some routes

Is this the right way to make a middleware for all routes with token authentication except /sign-in route?

const api = diet()

api.listen("http://api.example.sk")

const accountsSchema = new mongoose.Schema({
  firstName: String,
  lastName: String,
  email: String,
  password: String
})

const accounts = mongoose.model("accounts", accountsSchema)

api.header(($) => {
  let a = $.url.pathname

  if (a !== "/sign-in") {
    if ($.query.token) {
      jwt.verify($.query.token, secret, (error, decoded) => {
        if (error) {
          $.end("Token is not correct.")
        } else {
          $.return()
        }
      })
    } else {
      $.end("An unknown error occurred.")
    }
  } else {
    $.return()
  }
})

api.get("/sign-in", ($) => {
  let email = "A"
  let password = "B"

  accounts.findOne({
    email: email,
    password: crypto.createHash("sha256").update(password).digest("hex")
  }, (error, account) => {
    let response = {}

    if(account) {
      response = {
        token: jwt.sign(account, secret)
      }
    } else {
      response = {
        response: "The data do not match."
      }
    }

    $.json({response})
  })
})

Only this is the right way?

api.header(($) => {
  let a = $.url.pathname

  if (a !== "/sign-in" || a !== "/sign-up" || a !== "blabla") {

  }
}

Better Implementation of Protocol Handling

We should discuss here how to modify diet.js to handle simply all protocols via the current protocol/name shema

--- needed Modifications

  • app.protocol looks in /app/protocols/name first then in dietjs so we can overwrite the create server method to return any server we whant to have (net for tcp)

maybe a method for registring protocol handlers by name in the app object as like

app.protocolHandler('http', '/app/protocol/http.js')
app.listen('http://host.tld')

Lets us only use console.log if no silent mode as also fix to show console.error

I think we should add some debugging stuff there are some handy debugging infos we gain at present via console.log as also we get errors in the console.log thats not a good thing!!!!

we should change that console.log infos only get posted if not in silent mode as example we got in server a console.log for location none set right that should get console.error() so it gets logged in the right file and that

all other console log msges should get dispatched only if none silent! so we should make a console.log function that only logs if none silent we call it diet_console()
the function should check if silent is not set and then dispatch console.log

i assign my self to this 💨

Diet throws error on Node 6.0.0

Example code:

var server = require('diet');
var app  = server();

Result:

 Diet  (0.10.4) ☺
 http://dietjs.com/

/Users/kirill/Sites/realty/node_modules/diet/index.js:68
                initialized = true;
                            ^

TypeError: Assignment to constant variable.
    at Server (/Users/kirill/Sites/realty/node_modules/diet/index.js:68:29)
    at Object.<anonymous> (/Users/kirill/Sites/realty/index.js:9:12)
    at Module._compile (module.js:541:32)
    at Object.Module._extensions..js (module.js:550:10)
    at Module.load (module.js:456:32)
    at tryModuleLoad (module.js:415:12)
    at Function.Module._load (module.js:407:3)
    at Function.Module.runMain (module.js:575:10)
    at startup (node.js:159:18)
    at node.js:444:3

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.