Actually, most of the answers are wrong or misleading.
Normally JavaScript runs only in the browser and each browser has it's own implementation of how to run it. Node.js allows JavaScript to run outside of a browser by using the open source JavaScript engine developed for Chrome called [V8](https://en.wikipedia.org/wiki/V8_(JavaScript_engine\)). The V8 engine is what actually compiles the JavaScript to machine code... and it's really fast.
It actually has nothing to do with the web, but since JavaScript is only used by Web Developers, naturally that's what it's used for most often. It also has the unique advantage of allowing "isomorphic code", which means the frontend and backend can not only be written in the same language, but share the same exact code and files.
It doesn't really work like PHP, but rather more like Python or Ruby. It's just scripting, but using JavaScript outside the browser. Nothing more. To run a website with Node.js, you must use Node.js to create a web server that listens for HTTP connections, so your web server is Node.js. Where as with PHP, you use a webserver like Apache or NGINX to do this for you and then forwards it on to a PHP module. And just to complicate things further, Apache/NGINX can work as load balancers, routers, and are actually much better at serving static assets (css/js/images) and are usually used in front of Node.js.
I'm sure you've heard of the Express framework or the MEAN stack. Express is less like Laravel and more of just a web server implementation for Node.js. If you want a more complete web app framework, like Laravel or Rails (Ruby), then you should look at Sails.js (which is built on top of Express).
Install and use body-parser. var bodyParser = require("body-parser"); app.use(bodyParser.urlencoded({extended:true})); app.use(bodyParser.json()); // To accept data in the form of json.
If you have an input of:
<input placheolder="Select a number" name="userNumber" />
The data will come in the form of:
req.body; // All form data. req.body.userNumber; // The user number.
express documentation body parser You might want to watch the node.js series from the net ninja channel on youtube.
Um, looks like reddit isn't displaying the 11 comments on this post. I'm sure somebody already recommended Express, which is not outdated and doesn't have too much needless stuff if you're looking to write a web server.
You're comparing the wrong things here, Rails is a framework that runs on top of Ruby. Node.js is not a framework, it is simply a thing that lets you run javascript outside a browser. The closest equivalent to Rails would be something like Express.js, or Koa.js , or Next.js.
No, <code>get()</code> and <code>sendfile()</code> are not "nodejs functions"; they are only methods provided by the Express framework.
Therefore, there's no reason whatsoever to expect them to be treated like Built-in Nodejs functions.
The way you indicate errors to clients is HTTP status codes. 400-level codes indicate problems with the client side of the request (e.g. not enough permissions, requesting a resource that doesn't exist, bad query parameters) and 500-level codes are for errors in your server itself (e.g. can't connect to DB for some reason). When clients receive these status codes, they will know that the request was not successful and can handle the error appropriately for their use case (throwing, displaying an error notification, retrying, etc.)
In your application, if it's a client-level error, you'll want to set the status code using res.status
, e.g.:
res.status(400) // Bad Request
For handling server level errors, you should probably lean on Express's error handling mechanisms.
https://httpstatuses.com/ is a nice resource for learning more about status codes.
console.log
with return fahrenheit;
etc...Here's a fun test for you - run a GET request on '/employees/delete/employee/id' - you'll see that the GET "/" route in your router is called.
You've got duplication in how you're using your router. You can just declare app.use("/employees", router) and all of your routes starting with "/employee" will be handled by your router. All of your other "app.use()" statements are redundant and will cause unintended issues.
You should rename your router to something more descriptive, like employeeRouter. Then for each resource you have, you should have an appropriately named router that your app uses to manage said resource.
I really recommend reviewing the Express docs on routing. If you've only got four routes, having an separate file for routing is a little overkill. You should really only modularize if you need to.
You can do with body-parser middleware. http://expressjs.com/en/resources/middleware/body-parser.html A lot of things you can do with middlewares. http://expressjs.com/en/guide/using-middleware.html#middleware.router
> express has a lot, restify has a couple, the rest, not much
I think you answered your own question about "preferred frameworks." Express has tons of examples, tutorials, and over 16000 related packages on NPM.
There are several major versions of express, so see what version the tutorial is teaching before reading it. For example, the current version is express 4. An express 3 tutorial might have things in it that are wrong or no longer relevant in express 4.
The docs on expressjs.com are pretty good, so I'd start there.
NodeJS is essentially a javascript based runtime. It's whatever you want it to be. It can be used as web server (like http://expressjs.com/), or even an automation tool (like http://gruntjs.com/). People who are strong with javascript will like it. It's quite handle to do quick jobs or create a running a prototype in a hurry. Setup and learning curve is quite easy if you already know javascript. I have never used it in production environment however.
You are correct, backbone doesn't have a built in way to communicate with the database. But it does have a mechanism to perform updates by easily serializing the data and passing it to the server via an ajax call.
If you're building a web app, node alone might require a little bit of work. Since you have to write a lot of the web framework plumbing yourself (node is more of a low level thing). However, you can use Express.js which takes care of all that for you. http://expressjs.com/
From express api:
http://expressjs.com/en/api.html#res.cookie
res.cookie('name', 'tobi', { domain: '.example.com', path: '/admin', secure: true });
res.cookie('rememberme', '1', { expires: new Date(Date.now() + 900000), httpOnly: true });
i suggest you to use a template engine like pug.js
here is the documentation from express : template engines in express
This is a bit pedantic, but non-JWT cookie sessions like Express's cookie-session are also signed server-side, so you can be sure that the user hasn't changed the value (unless they've stolen your key.) That's the same as with JWTs.
What's neat about JWTs is that an end-user can read the information even if they don't have the signature key. Unfortunately, when you lock JWTs behind httpOnly cookies (which you should!) your end-user can't read the information after all.
You want to build an API endpoint. Something like
app.get('/myEndpoint', (req, res) => { res.json(rows); });
For specifics you probably want to take a look at Express: http://expressjs.com/
Great question! Indeed, Nginx can serve static files just like Node JS. At first glance it may seem redundant, but there’s more to the picture.
Nginx has a lot of optimizations to serve those static files and respond to web requests more quickly. More on this point here: https://stackoverflow.com/questions/9967887/node-js-itself-or-nginx-frontend-for-serving-static-files
Nginx also provides a world of flexibility via simple configuration files. Nginx can act as a reverse proxy, to redirect http requests to other servers/ports/microservices/etc. Setting this up is simple as altering a configuration file and allows many rule based routing configurations (like based on url path, port, etc). Nginx also helps with load balancing, so if you have all requests first hit Nginx, it can then redirect requests to other servers using a variety of strategies (round robin which just takes turns sending the next request to a different server, weighted average which allows you to specify what % of all requests each redirected server gets, etc.)
Express documentation even recommends letting Nginx handle static files, leaving your Node Js code to handle dynamic API requests.
http://expressjs.com/en/advanced/best-practice-performance.html#proxy
All this is not to say Express/Node JS is bad for serving static files, it is fine, but Nginx is considered a best practice.
A few things wrong with this --
Passing anything to next
invokes the error handler. Seems you have the error handler with user
as first parameter -- so while this "works" it probably isn't what you want.
Assuming the following middleware --
const middleware = (req, res, next) => { if (req.user) { console.log('we have a user!') else { console.log('no user here') next() }
There's a few ways to attach middleware --
// global, applied to all routes app.use(middleware)
// or via a router const router = new Router()
// can be applied globally to the router. note that you must attach the router to app or another router via a prefix, or it'll be applied to all routes at that path level router.use(middleware)
// for a specified route router.get('/path', middleware, (req, res, next) => {})
// you can also do above on the app level app.get('/other-path', middleware, (req, res, next) => {})
// (always make sure you attach router with a prefix) app.use('/prefix', router)
Take a look at the docs http://expressjs.com/en/guide/using-middleware.html
There's nothing wrong with using csv files for storing small collections of records. A database will start to come in handy if you ever want to store large amounts / perform complicated queries on your data.
A nodejs application would work. Many existing tools use a locally hosted web server to provide some kind of ui. As long as the server never exposes itself to the internet (i.e. only bound to localhost) - you will be fine.
NodeJS has the expressJS library which will take care of generating templates, starting the server etc.
The "backend" of a website encompasses its database and the code that interfaces with it. e.g. an Express API (written in Javascript run via Node.js) that exposes REST endpoints for performing CRUD (Create Read Update Delete) actions against a database would be considered "backend" work. You can think of "frontend" as the presentation aspect of a website - the manipulation of data into a presentable and viewable form. The "backend" encompasses the processes by which that data is obtained and interfaced with in the first place.
Other backend or server-side technologies (aside from Node.js) include Java, .NET, PHP, Ruby, Python, etc. Most languages have a web framework either built into them or installable via a package manager. In the case of Javascript, since the language was designed to be run within the context of a web browser, we have a runtime that allows our servers to interpret Javascript as well - that's Node.js and V8.
Here's a helpful blog post https://blog.bloc.io/frontend-vs-backend-web-development/
These are the most common tools in node development.
Why are you looking for MVC in particular? Most of the node/js community has moved away from MVC in the traditional sense. I would suggest learning the tools above, especially express.
Rails is a fully-featured web framework for Ruby interpreters. Node.js is just a JavaScript interpreter, so if you want something like Rails you'll want to start checking out web frameworks for Node.js.
The most widely used web framework is Express. They have a getting started guide on their website, and if you search Google you should be able to find lots of tutorials for using Express.
I can't vouch for any "golden standard" books, but you can check out this book.
Just a basic Express app that runs on the same server as the database, and that connects to the database. It would have one GET route for each set of data you need.
Depending on your specific requirements, it probably wouldn't have to be much more than this.
app = express(); app.get('/data', function(req, res){ db.query('SELECT whatever your query is', function(err, result){ res.send(result); }); });
Be sure to implement authentication though, at least using a token header, otherwise everyone would be able to just access the data (unless that wouldn't matter, if it's a free to use public application then authentication would be less of an issue). But there are modules on npm for authentication so it's pretty easy to implement.
EDIT: if you don't know Express -> http://expressjs.com/
Nice. Actually, I'm slightly sure. I'm used to NodeJS where when you're writing servers, you do want an event loop to handle requests when they come in, so naturally you have to use some concept of observables. In Node, almost everything is an Observable, and an event loop actually helps with reasoning about code. Communication between observers isn't too bad, but in Node you always can register new observers (event callbacks) on observables (event emitters). I was just wondering if Haskell had any library like that, especially something like Express that has a nice API to write webservers.
Learn a back-end language. Use its most popular microframework to build a basic server. Create a "hello world" route (homepage) and go from there.
For example, for Javascript (Node.js), there's http://expressjs.com.
> Understood, I don't know how it works, but I know what it does.
Well, maybe you should start there first? Because there's tons and tons of documentation on how to serve static files with express, it's literally one line of code. The routes you're creating (for / serving an index.html) are primarily meant for serving dynamic content.
I also don't understand what the confusion with Socket.IO is: it uses the same HTTP server that express is using for websockets: so it will be using the same port (server.listen(80)).
You really should learn to learn: samples tend to only teach you ONE thing; you have to combine the different concepts yourself. You won't be finding any tutorials that show you how to build exactly what you want.
If it's not hard to control with an Arduino, I recommend and HTTP API written in nodejs using express: http://expressjs.com/ and controlling the Arduino with Johnny-Five https://github.com/rwaldron/johnny-five
I used this combo to make a web page where touching the page from my phone would spin a motor on the arduino. Whole thing was maybe 25 lines.
I feel like it is gonna be pretty hard to be a front-end developer if you have no idea of the back-end technologies. Maybe try learning NodeJs/ExpressJs super basics. Start by installing nodeJS, then learn to use npm(comes with node) to install express, then just run this: http://expressjs.com/starter/hello-world.html After that you can play around with express-generator and can get a pretty basic server running and build off it from there. You will have to learn about async callbacks eventually haha.
Then if when using Angular or Backbone you can customize a nice environment to practice in.
I know its overwhelming and bewildering but it slowly will start to clear up. I dunno anyone else can contradict me, but it always seemed weird to me to be purely front-end and have no clue about what was happening on the server at all.
Yes, they are completely different things.
gulp: a streaming build tool
express: a web application framework
You are likely using gulp to serve static content I assume. So you would instead use express, to serve your static content as well as handle your angular application routes. However, tbh, if you are a 'noob' I would try to get comfortable with the technology first before trying to do html5Mode in angular.
You're comparing RoR with node.js, a web development framework vs a platform.
I'll assume what you want is something like what RoR does but then with node?
You should start with express.js which is a micro framework like Sinatra in Ruby.
Most of the larger MVC frameworks in node have express as a dependency.
I think Sails.js is the most well known MVC framework for node and it should be quite similar to RoR from what I've heard.
From the Sails site: > It is designed to mimic the MVC pattern of frameworks like Ruby on Rails
Can't say for sure though since I don't have any hands-on experience with either RoR or Sails.
First off, I really hate "JavaScript The Good Parts", it doesn't actually cover the best parts of javascript, and a lot of NodeJS code is written in a style that the book claims is "bad". Check out this Guide to JS Prototypes so you can see how prototypes work.
The framework you should start with is express. Pretty much all other frameworks are built on the same concept with more features, so learning express first will make it easier to learn Sails or Meteor.
As for your second question, Github. Almost all nodejs projects are on github, so you can just check when the last commit was, or click the issues tab and see if there are a lot of open/ignored tickets.
Also, read more of other people's code. People here have like an allergic reaction to reading code, but it's the best way to learn these things!
That's a great list to start with! Though I like the idea of starting with small and concrete tools (Socket.IO, Async, request, etc), I think Express.js is difficult to ignore when working in big projects.
So, nginx has examples for routing wildcard subdomains to the same application: http://wiki.nginx.org/ServerBlockExample#Wildcard_Subdomains_in_a_Parent_Folder
After you've done that, you can add a middleware that will examine the subdomain to get the particular user and add it to the request: http://expressjs.com/4x/api.html#req.subdomains
EDIT: Just realized you wanted to add a Ghost blog to each user... That's a bit more complex.
Node is just the technology. You would need some kind of web framework if you don't want to handle all low level http stuff since you need to code the actually webserver itself with node. My recommendation goes to ExpressJS, check it out at http://expressjs.com/ .
I am a full-time Node.js developer and I agree with this 100%. I would implement this using Redis to talk between the C backend and your web frontend. Simply removing the disk bottleneck will give you a huge performance increase here.
Personal experience has taught me that nodejs is far easier to use and more portable than Apache + PHP - for one, Nodejs is simultaneously web and the application server.
You'll want to start with a simple framework like Express. You can use projects like node-redis for your Redis communication. Express will help you interact with templating. Use Socket.io for websockets on both the front- and back-end. Tada - no polling, fast performance, easy to maintain.
Depending on the complexity of your views I would say you could likely could pull this off in < 100 lines of code. All node has to do is connect to Redis, serve a simple template, and serve updated JSON through socket.io.
Edit: Note that you're just replacing the PHP middleman with a Node.js middleman. If you're not having problems right now, don't bother.
Taking a look at Realm of the Mad God (and being a backend developer myself), I would say that node.js isn't exactly the best server language to learn on, but it is probably the most appropriate for an MMO shooter like that. If it was a turn-based game I would definitely say keep it simple to start with and use something like Rails, Sinatra, Yii, Django, etc.
A node.js framework like Express.js or Socket.IO can make it a little easier and save you from callback hell. Using websockets will make legacy browser support slightly trickier, but it will allow you to update the client faster and much more often than polling.
Languages like PHP and Ruby are fine (and you could make either of them work just fine), but node.js is designed for high concurrency and much of what's out there for node.js is geared around that.
Also, at the risk of sounding even more "use all the flashy shiny new things", MongoDB's two-dimensional geospatial indexing can make your life even easier (call something like
db.tiles.find( { loc : { $near : [50,50] , $maxDistance : 20 } } )
to get all of the tiles near a player, for instance)
You could even just nest all of the state for a tile (whether there are objects/players/mobs in it, etc) in the tile itself and make your lookups even easier.
I went from creating my own for a specific need to using Connect to finally moving to Express.
To be honest, if you are familiar with Sinatra from the Ruby world, you will like Express.
I guess the best way to understand node's significance is to try and make a web app in something other than node. Once you go through the pain of trying to make any rich-ish web app in php or java you start to understand the benefits of a application written in node. Anyone can talk about the possibility of code sharing between client and server, or the close integration with web sockets and fast document-based database systems (mongo, redis). The express framework guide page has some good examples of how easy some functions can be in node.
The proof is in the pudding. Next time you wanna write a web app, try it in node!
> How can Express possibly "just work" when it's missing basic features modern Js libraries and syntax use? Promises, error-handling, timeouts
My company's node projects have been serving tens of millions of requests every day for 5-6 years now. That's a whole lot a billions of requests total. Our code uses Promises extensively, has clean and complete error-handling, and every single request has a timeout feature. So I have no idea of what you are talking about, or maybe you have no idea of what you're talking about.
> That's just the reality of software, and the longer it's left unmaintained, the more people will just rely on it thinking it works, when in fact, nobody is even checking if it really does anymore.
You use the word "fact", yet you don't give anything to back up your claim.
Don't get me wrong, I'm not saying that Express, or any software for that matter, is 100% secure. All I say is it's secure enough for companies who handle huge workloads and sensitive stuff (mine does in both cases).
usually I use nodejs
I tried, but I couldn't get it to forget a route once it was set, like it would kind of do it...but not totally and leave relics of the route hanging around causing issues if anyone tried the path after it was 'removed'
I believe this is because I was too inexperienced with nodejs express routing, the answer seems likely to be found in the 'router' function that works in conjunction with the express app when a route lights up.
Client side:
const data = { key0: "value", key1: 1, key3: ["foo", true, null] };
fetch("http://www.your-url.com/", { method: "POST", headers: { "content-type": "application/json" }, body: JSON.stringify(data) }) .then(({ json }) => json()) .then((json) => console.log(json));
Server side:
You can use Express middleware (body-parser) to read the body of requests: http://expressjs.com/en/resources/middleware/body-parser.html
Separate in your mind frontend and backend code. Your frontend / user interface runs in the browser and is built with JavaScript/HTML/CSS and/or a framework like Vue.js or Angular.
The backend code runs on the web server and connects to a database. What you choose (code plus database) depends on your web hosting provider. Many people pick Ruby on Rails for a backend language that includes a database. PHP is an older server-side language often used in combination with a MySQL or SQLite database. It's easy to set up and widely supported by almost all cheap web hosts.
Now I'll answer your question about using JavaScript for a backend: Yes, a great option while you are building and learning would be to use a node.js web server where your backend logic is written in JavaScript (same as frontend) and can easily connect to a SQLite or other database.
If you want to get going quickly, ExpressJS is a node.js framework that can build you an entire working starter web app with a just a few commands.
You could take a look at Eclipse Che, an online IDE.
My suggestion is that you should try to build those example on your machine, in order to get a better understanding of the build/deploy process. Even better, you can start a project from scratch (depending on what you want to learn, there may be tools to get started like Express Generator for Express (Node.js) or Spring Boot for Java) and try to replicate those example yourself.
using the documentation on http://expressjs.com/en/api.html#req.get You can use something as follows: req.get('Content-Type'); // => "text/plain" Replace Content-Type with header name to get value. You should be setting your header values in your app constructor. Hope that helps.
Express will give you a fast start if you want to serve websites. It will also help you understand (part of) the pottential of Node. It will make your learning funny. But mind that Express is just part of what Node can do.
It makes building web servers quicker and easier. You should give it a try and move on to other things when you feel comfortable. Start by reading the API to get a feel of what it can do.
http://expressjs.com/en/4x/api.html
Does it have to be a GET request?
I didn't understand whether or not you succeeded in getting the data into the view, but you can send the parameters of the path to your ejs/view file, using express.
In theory:
res.render("/form", { field1 = req.params.field1, field2 = req.params.field2 });
Then your data would be accessible in the view.
Can you share the code for the form and the router that handles the form?
This will help in "simplifying" your journey:
Using some sort of MVC (Model, View, Controller) structure, typically. If there's only one pattern you should know when doing backend webdev, this is the one.
Also Express has a generator that can be used as a basic starting point.
I think knex will give you a few different kinds of errors differentiated somehow, things like query format error, trying to insert a taken unique id, loss of db connection. Play with that and see what it looks like. Then you have to tell express how to handle that error. You might just pass the error to the user in a template, or you want express to bomb out and handle the error like this
From: http://expressjs.com/en/guide/error-handling.html
function logErrors (err, req, res, next) { console.error(err.stack) next(err) }
I think graph QL would be overkill probably... I'd just set up some Express routes with a few simple HTML templates to render connected to the C apis either directly via http or with a couple helper functions. More than plenty to start with. The express docs, http://expressjs.com/ , have everything you need.
You need to create more Views. Check this out - EmbeddedJS
Also you need to render views rather than sending files.
Use res.render(......)
Check out express documentation as well for rendering static files - here
req.query
This property is an object containing a property for each query string parameter in the route. If there is no query string, it is the empty object, {}.
// GET /search?q=tobi+ferret req.query.q // => "tobi ferret"
// GET /shoes?order=desc&shoe[color]=blue&shoe[type]=converse req.query.order // => "desc"
req.query.shoe.color // => "blue"
req.query.shoe.type // => "converse"
From here http://expressjs.com/uk/api.html
What you need to do is to turn your node js app into a web application. You can use Express.JS and write a very simple web app.
You will need to write couple of 'handlers' this way:
app.post('/getpdf', function (req, res) {
var html = req.body.payload;
var filename = "dynamically_generate_this_file_name.pdf";
Prince()
.inputs(html) //Warning: direct string input. You may need to convert to buffer
before using the html. consult Prince's documentation. I am sure theres a way.
.output(filename)
.execute()
.then(function () {
res.send({ url: "/"+filename });
}, function (error) {
console.log("ERROR: ", util.inspect(error));
res.status(500).send("Something horrible happened. Kittens probably died");
});
});
// another handler
app.get('/:filename',function(req, res){
//You need to pipe the file contents from local disk to 'res'. There are plenty of
//examples for this in Express.JS on
//how to do this. But if i remember, this is a simple way to do it.
res.download('/'+req.params.filename); }); In your javascript in the client side do this:
<script> $('#generate').click(function(){ $.post('/getpdf',{ payload: $("body").html() } ).done(function(result){ if(!!result && !!result.url){ var link = "<a href='"+result.url+"'" target='_blank'>Download pdf here ! </a>"; $("body").append(link); // obviously append this somewhere appropriate. } }).error(function(){ // warn the user that earth is on an imminent collision course with sun }) }); </script>
I wrote all this without checking any of it. You may need to correct references here and there, install express.js (Its stupidly simple). But you get the jist of it.
Sure, it's not the main problem, but in situations where you're convinced you need that many parameters, putting them into objects is usually the best solution. There are many well-written modules that have to allow a dozen optional parameters (e.g. express.static), and stuffing them into an object is the go-to approach.
Without getting tooo into it, here are -roughly- the steps you need for this to work properly.
Your server (it looks like your app.js file is the point of interest) needs to have an endpoint that expects a post or a put. You can see more about using post with express here: http://expressjs.com/en/api.html#app.post.method
You need to hook up this endpoint to your database, so that when that callback function fires with the (req, res) params, you can successfully receive the request(req) and insert whatever information you want from it into the database
You need to then use the res portion of that callback to respond to the client when that's all done - generally you want to provide the information that you just inserted back to the user so they can react off that, or if there are errors you want to send one of those back too. Not super important to get tooooo deep into this part for now, but you do need to send back a response unless you want your request to time out.
From your actual angular application, you now need to send a post request in that 'like' function - something like $http.post(someUrlEndpoint, dataToSendOver). This returns a promise so you can then handle any responses from the server in the .then()/.success()/.error() you attach to this promise. For example, if you send back an error, you can display it to the user. But keep it simple for now, focus on just getting that full cycle in.
To break it down - create a post endpoint on your server, hook up post endpoint to your database, update your database with information, and after that is done send a response back to the client. On the client, send a post request to this new endpoint with the data you want to save, and handle any responses from the server.
I haven't done much with PHP, but one of the biggest differences is a NodeJS application is a server. PHP has a file for each url. Express.js's "Hello World" example is a good example:
var express = require('express'); var app = express();
app.get('/', function (req, res) { res.send('Hello World!'); });
app.listen(3000, function () { console.log('Example app listening on port 3000!'); });
This is an HTTP server. You don't need Apache or NginX or anything in front of it. You can have a url per file or not. In fact node doesn't even come with url routing (Express.js is a very common framework that does that). In fact you could have an application with thousands or urls in a single file (though I don't recommend that).
Also you should look up and understand asynchronous callbacks/Promises/generators/async and await if you want to do serious Javascript. They appear everywhere because that is how Javascript (and Node) do many things at once.
Agreed with /u/Nenai.
If you're trying to get work done and actually build a product or service, just use what you're best at (Rails) and get it done.
If you have a toy idea that you're playing with on the weekend, then it's a good opportunity to learn something new.
In my experience, it's rarely a good idea to mix the two.
Node is cool but not necessarily going to make a difference in how you build webapps. You'll be using a microframework like http://expressjs.com/ and it's going to feel just like building something with Sinatra. But what I like about Node is that the ecosystem is built around the Sinatra mindset rather than the Rails mindset.
Although I use Web Api 2 professionally, for small projects I found Node.Js/Express.js to be the easiest for setting up endpoints (whether it's the best for professional solutions is another discussion).
http://expressjs.com/en/guide/routing.html
You can use a host like Heroku which makes it extremely easy to setup online for anyone to use your API (they also provide a free version for developing). If you're willing to spend $10/year, you can also buy a custom domain to tie to your API (which, again with Heroku, takes all of a minute to setup).
Look up how to make an express server (node) serve static files, it's like 4 lines of code to have a rudimentary server going. You make that guy listen on port 80, which requires sudo/root unless you configure it, with your digital ocean box running ubuntu, which is the easiest way to start, you can then go to your boxes IP and you'll see whatever folder you choose for static.
You can also look into nginx or apache but a static express server is incredibly easy and will be an OK way to get your feet wet. It is not actually a good way to serve static stuff at any scale, but you really don't give a shit yet.
here's a link http://expressjs.com/en/starter/static-files.html. so your node app.js
would be
var express = require('express'); var app = express();
app.use(express.static('public')); //folder name
app.listen('80'); //to serve from 80 you need root perms, can test with any port
And you're off. sudo node app.js
will start it. Be sure to do the digital ocean basic setup stuff to lock down your box at least a little bit, they're pretty open by default.
I started just like you're intending to, diving right into the deep end. It worked great using node and screwing around with baisc UNIX stuff. Plenty of good tuts on digital ocean, and it's really not incredibly difficult if you take time to understand everything. Good luck!
Unfortunately I don't think there's a simple walkthrough but I'll give you some general direction. If you're still interested after reading this/checking the example and need further help, PM me. If not, someone might find it interesting anyway.
Here's an example where I'm using this ability to execute scripts to give me live information about my Pi (updates every minute or so):
http://i.imgur.com/JWZFAMG.png
So first, I would recommend to check up how to serve simple web pages using node.js (there's tons of tutorials out there), and I would also recommend you to use the Express framework. It's also recommended to use npm for dependency management, it makes your life a lot easier.
After all that, the simplest case would be to listen for a GET or POST request and execute the script. Here's an example (somewhat incomplete):
var express = require('express'), app = module.exports = express(), execSync = require('child_process').execSync;
(...)
app.post('/getpitemp', function(req, res){ var temp = execSync('~/website/scripts/bash/pitemp.sh'); res.send(temp); });
(...)
It's self-explanatory, but basically it listens for a POST request ('/getpitemp'), and after requested, it executes the script and returns the output of the bash script. If you don't need the output, that's fine aswell.
EDIT: Oh also, this might be useful for someone: If you are developing something like this, develop on your main PC and then just use rsync utility to sync files with your RPi.
Use the Express generator.
http://expressjs.com/en/starter/generator.html
All this does is set up some boilerplate for you. It is not a framework, Express is the framework. You can start making an Express app in about 10 lines of code.
Mongo is the database. Express is the backend framework. Angular is the frontend framework. Node is the runtime. The only one of these things you need to use is Node. Feel free to replace any of them as you see fit, such as React instead of Angular or PostgreSQL instead of Mongo.
You can use
res.sendFile("./test2.html")
but it would resolve the file name relative to the path you where execute the application.
Take a look at res.render(), it might be a better solution.
BTW, using path.join is safer when you're dealing with file paths:
res.sendFile(path.join(__dirname, 'view/', 'test.html'));
app.locals
http://expressjs.com/4x/api.html#app.locals
I always toss my DB instance there, along with models or anything else I don't want to require on every single routes page. You can pass your app
instance around to your routes includes, or just use req.app.locals
.
You can try following the Getting Started Guide that Express has on their website.
You're right that Node isn't the best for beginners, since most resources assume you know what you're doing already. Maybe I'll start a beginners blog for Node sometime. You can try this one for now.
Personally I would recommend learning JavaScript (if you haven't already) and using Express.js. Here's the guide for building a Hello World example.
You'll most likely have to pick up JavaScript on the client-side anyway no matter what you use on server, so at least you can stick to one language while you learn.
There is express.js, which is a server- side framework for Node. Also, Node performs very well, so don't get too hung up on efficiency.
it's an express app, so start with the official guide and skip to "Run the app", maybe that will work.
beyond that, ask the people that created it. onus is on them to make proper documentation.
Route to your handler while considering the HTTP method, you'll likely want to process session information and other parameters with that identified handler (you could also have some middleware process as you follow down the requested route.)
While I don't know of any tutorials/books to suggest, Express' documentation is a good read that will show you some examples of routing/route parameters/queries. It may provide you some ideas to incorporate into your API (if you haven't read it already.)
Edit: nitpicking and grammar stuff.
JScript? As in Microsoft's abomination? Ignore that...
You need to have something run on the server to host JSON or to interact with a client side tool? If you want to keep most of your existing JavaScript, Node.js would probably help you out. I've built quite a few Node Express servers to simply generate JSON data for testing and mocking.
--Edit: This is a simple way to send JavaScript Objects as JSON objects:
app.get('/api/path', function(req, res) { res.json(myObject); }); --End Edit
Also, you will not be using Document.Write() FYI. You'll be sending your JavaScript Object as the response.
As far as concurrency, don't worry about that right now. Get it running, then look into the options when you have it running and find out if it is performant enough (Node is pretty damn good for lightweight tasks and scaling up has several methods)
As far as I know, the header doesn't really do anything. It just means that express is being used, kind of like the x-powered-by php header.
Express.js is used a lot in node applications to handle routing urls. http://expressjs.com/
Backbone and Angular are front-end frameworks.
React is a front-end framework but with some (imo) hackery you can also use it on the server-side and client-side. But I wouldn't recommend it to beginners that are confused about the difference between the back-end and front-end. I think it would just make things even more confusing.
I recommend using a back-end microframework for Node. Express.js is the most popular and minimal one. It's easy to get started with.
I wouldn't even worry about using a front-end framework until you understand how to build a 100% server-side app with Express. I think this would be the most obvious way to understand the difference.
There is /r/learnjavascript if you need to learn the basics.
It really depends what you want to build:
I mention these based on your own suggestions. Of course it is possible to mix and make use of different tools together. You can make full-stack apps with Express + Angular for example.
So you need to figure out what you're interested in and then it is easier to know what to learn.
After that I would try out the ones you find most interesting and make a sample project. You will find out what works best for you.
Note: you will not get very far with React alone. It is only the view. You will still need someting like Flux (or an implementation of Flux) to create a full application.
I've yet to see a mainstream stack do it well. I also tried the Backbone method once and found it wanting. Better than not going isomorphic though. Seems like the best way to do isomorphic stuff is an area of active research. I hear good things from the React crowd, but I've yet to try it.
If I was building a fresh app today, I'd go with Express on the server, page.js on the client, and share controllers with this page.js plugin I wrote. This approach will work with any templating system that's compatible with Express (so pretty much any JS templating system).
Ah yes, my mistake - I completely failed to see the express.static
middleware you used.
The rest still applies, though; unlikely Apache, Node.JS won't automatically serve index.html
when accessing the route /
. If you want to serve a specific file at a specific route, use something along the lines of <code>res.sendFile</code>. Then simply linking to /app.js
in your HTML file should work (assuming you're using app.use
correctly).
>It is not meant to pass a script to the browser.
Isn't this precisely what the docs direct you to do? App.use is for serving static files. Maybe the phrasing is backwards, app.use is for responding to browser get requests with static files?
Nitpick: it looks like you're using Express, which is totes a popular web framework ;P It's just slim is all :)
You had me worried for a minute. Building your own framework can be incredibly educational, but, in terms of the product's security and maintainability, it's much stronger to say that it's built on a well-established framework like Express.
What's the auth stuff built on? That's the part that's really hard to get right. Some of it looks homegrown, but maybe it's running Passport or something under the hood?…
edit: Never mind, there are some hints that the auth stuff is running on Skeleton, which oughta be sufficiently robust :) Carry on, and consider being open about what you're using! No shame in using great tools! :D
It seems we turned the scales... your question is getting upvotes.
I wish your engine came out two years ago. I was fascinated by haml on RoR and jade on express, but PHP's haml interpreter did only support a subset of markup and I had to turn to Twig to get my current project started.
At least having so much logic in Twig made it easier for me to convert part of it to Handlebars when I decided to go for a Single Page App approach.
Set up a few bots using node-steam. This requires some programming but it's not that hard nonetheless.
Rent a VPS at a random hosting provider.
Install an OS on your VPS, such as CentOS or whatnot. Have Forever keep your bots alive.
Install Express to handle web-requests.
You get the idea. Setting this up takes 1 afternoon, apart from programming the bots and having to wait for Steamguard.
Meteor is a complete stack which relies on Node.js and other components. If you like "ready to go" solutions, go for it.
You can try other solutions involving node.js (like node + express + mongodb) . Node's package manager (npm) is very good. ( http://expressjs.com/ )
For the scalability, like any other platform, it depends of what you're doing with it...
https://www.discovermeteor.com/blog/scaling-meteor-the-challenges-of-realtime-apps/
If you are serious about Node development, then you will eventually determine your own project setup. However, if you just want a quick start to kind of see how things work, check out the <strong>express-generator</strong> npm package.
Have fun.
looks like a node.js server (though that is just how it's identified in HTTP headers).
X-Powered-By: Express
He's probably using express as his web server. So node.js is probably the back end. It goes through a proxy called vegur which has node.js smell after googling.
As /u/menno says, res.render
sends over html and headers...<code>app.render</code> can be used to render a partial and not send the results back to the client.... but even then, you'd need to keep all those partials in an array and join them together after going through all of them.
An easier way may be to pass the entire array to the template, where you can do the iteration :
... if (result) { res.render('pages/index', { results: result }); } ...
<%results.forEach(function(result){%> <span class="regionname" id="SelectedRegion"><%= result.RegionName%></span> <%})%>
Assuming you don't call res.render anywhere else, you shouldn't get that particular error.
One thing to look at may be the Async library... it is pretty good for async callbacks of all sorts. In an express context, you'll do all your async code above and in the finish block you do your res.render or error handling.
depends on what you want to do.
If your question is really specific to express and express generator, the bast I can do is pointing you to the express-generator documentation:
http://expressjs.com/starter/generator.html
As it's intented to be used as a cli tool, makes more sense to install it globally.
If you are looking for the Express routing stack:
Every Express application uses an internal router: app._router
You can access the router stack: app._router.stack
Take a look at this thread: http://www.reddit.com/r/node/comments/2jkzv6/express_is_there_a_way_to_find_out_the_router/
But you probably just need to read the Express documentation about Routers: http://expressjs.com/4x/api.html#router
Here's how I did it:
Step 1: know how HTTP works (browsers issue GET requests when clicking links / entering URLs in the address bar, forms POST by default, XHR lets you do whatever method etc). You mentioned you already have web experience so it's likely you already know this: if not, the Wikipedia pages on HTTP break it down pretty effectively.
Step 2: Know JavaScript, specifically how functions are first-class values (ie. you can make anonymous functions and pass them as an argument to a function). Again, since you mentioned you have web experience I'm assuming you know this.
Step 3: go over the API at http://expressjs.com/api - it's pretty straightforward. You give it functions to call when somebody makes a request for a certain kind of path (eg. when somebody GETs '/clock'). It'll call those functions giving you an object to read stuff about the incoming request, and an object to write the response. (If you take three arguments, it will also give you a function to pass the flow of execution / errors to, if you don't want the response to end at your function.)
Step 4: Assuming you want to make web pages, know HTML and CSS. It sounds like you already understand this to your satisfaction, so that's good.
Step 5: While you can just write functions for every page that build the response as a string and pass it to res.send()
, it's generally a smoother experience to use the express.static()
middleware to serve static assets like CSS, and use a templating language like Jade for page HTML.
At this point, it's generally best to start reading examples of other apps: I've written lots of Express apps, but plugmap.com is probably the most straightforward.
> And the above code is for Express 3.0. The following code is for Express 4.0+, where most middleware has been explicitly removed from Express.
Yep, most - actually the only middleware still included is static. As per the docs; > As of 4.x, Express no longer depends on Connect. All of Express' previously included middleware are now in separate repos. Please view the list of middleware. The only included middleware is now express.static().
Wikipedia was an extremely helpful resource for me in this regard. I liked it because I could drill down to whatever depth I needed for material that I didn't understand. Once I knew enough about what was happening between my browser and the servers, the next step was writing a small RESTful service of my own.
For example: Make a RESTful personal to-do list service. Each user of the service has a list of items, in text, and they can add/remove/edit/view them. New users can sign up. Don't worry about password protection or how the pages look or anything fancy like that -- first just make the basic to-do list functionality work. You won't know how to code this yet, but once you do a bunch of reading about REST, and a bit of reading about frameworks used to create such services (examples include Rails and Express), you'll have the tools and the knowledge you need. Good luck!
> I used this format for grabbing param values, and I'm not sure I understand the req.query.query way you described:
> var query = req.params.query;
> I think I'd be more inclined to intuitively do this:
> var query = req.param.query; var dateSelection = req.param.dateSelection;
> Am I thinking on the wrong lines, or was that a typo?
req.query is the parsed query string. req.params are the parsed url parameters. The query string is everything after the ?
in an url.
e.g.
http://localhost/post/1?q=test
with the mapping
router.get('/post/:id')
will result in a req.query being { q: "test" }
and req.params being { id: 1 }
For more information look at docs for request query and params
To expand a little on what RodionGork said: node.js is an interpreter for Javascript that lives outside of a browser. You can write Javascript code and run it in node, or open up node and run Javascript commands one-by-one.
It's used most often as a server for web applications -- and while it's not really a framework on its own, frameworks (like the very slick express.js) have been created for it. You can also use it to develop command-line applications -- compilers for languages like CoffeeScript (which compiles to Javascript) and LESS (which compiles to CSS) run on node, and are sometimes used without node acting as a server at all.
I haven't used it for any big, serious projects, but my impression is that its only real disadvantages are the ones it gets from Javascript itself. And if you like the way Javascript does things, that may not be a big deal. I'd welcome feedback from more experienced node devs, though.
A framework is a set of development tools that allows you to develop something. It's usually composed of compilers, libraries, tools, APIs, and anything else that's needed to develop in the target environment.
An API (application programming interface) is usually a set of libraries/tools that you would use in conjunction with a framework to extend your application. In the web world an API is usually a set of functions provided to you by a 3rd party application that allows your application to inherit some functionality or data from the 3rd party application. For example, Twitter has an API that allows your application to post/retrieve messages. Sometimes an API is a JS file you import (for example the YouTube Player API), and sometimes it's simply a feed (YouTube Playlist API) that you query using AJAX/AJAJ.
Node.JS allows you to run JavaScript on your web server; it's a service provider, and could fall under the "compiler" category of a framework. It's not a framework by itself though. Though if you were to package Node.JS scripts, Node.JS, a SCSS compiler, and some JavaScript APIs together, you would get a framework (see http://expressjs.com/).
This is a simple wrapper around the Node cluster module that I wrote, comprising solutions to the most common problems I need to re-solve each time I write a simple Node application.
It speaks in Unix signals, so TTIN
and TTOU
fork and decrement workers, respectively, and INT
forces immediate shutdown, and TERM
/QUIT
initiate a graceful shutdown with a timeout until forced shutdown.
The exported function accepts any old request handler:
var clusterflock = require('clusterflock');
clusterflock(function(req, res) { res.end('ok'); });
Which means you can also pass it your express app:
var clusterflock = require('clusterflock'), express = require('express'), app = express();
clusterflock(app);
I mostly wrote it to provide a way to decouple my frequently-used server setup in most of my Node.js web apps from the application logic/code repository itself. It uses node-logfmt to provide pretty verbose logging that serializes back into JSON, if need be.
I rarely use Node without Express. It simplifies many tasks, and if you are building a website, I wouldn't go without it. The site explains pretty well how to use it for basic routing, rendering views, database stuff.
npm install express -g express myapp -c stylus -t jade cd myapp && npm install node app.js
Will create a new Express site, using Stylus for styling and Jade for templating. Web development on crack.
Images need to be sent to the server via something like a multipart form request. I usually use multer to handle it.
http://expressjs.com/en/resources/middleware/multer.html
You probably don't want to write the file data to your database but rather to some sort of storage and save a reference to it in the db. In firebase for example this would mean writing the image data to cloud storage and saving a reference in cloud firestore.
Args are backward http://expressjs.com/en/api.html#app.listen: app.listen([port[, host[, backlog]]][, callback])
The first thing you should do when hitting an unknown error is read the docs and make sure you're calling the function correctly.
Adding to this, it looks like you might be using express’s body parser. If so you can use the JSON configuration to have this done automatically.
http://expressjs.com/en/resources/middleware/body-parser.html#bodyparserjsonoptions
These are callback functions which are taking multiple arguments, they are not returning multiple arguments.
Essentially what is happening is app.get() is assigned to the ‘/‘ endpoint of your app, along with an anonymous callback arrow function which accepts two arguments ‘req’ and ‘res’.
When the ‘/‘ endpoint is hit with a GET request, express knows that it needs to call the previously assigned callback function with the request and response objects as the arguments.
I recommend checking out JavaScript.info for fantastic break downs of all JS features.
Checkout Express app.METHOD documentation for a detailed explanation of this example.
You can also read the MSDN Callback Documentation
It's not a bad practice if it was encrypted similarly to how JWT is encrypted. If you use this one session middleware - it doesn't store any data in the cookie at all, so for answers check readme of the specific library you are using
Attaching data to res.locals is the recommended way to do it in the Express framework.
You also may want to take a look at continuation-local-storage. It’s a great way to maintain a session for the lifecycle of the request.
You might try to use a RegExp in the array config for origin, that will allow you to match any sub domain of mysite.com and, at least, eliminate the hard coded http protocol as a troubleshooting step: http://expressjs.com/en/resources/middleware/cors.html
Also depending on the http method you are using you may need pre-flight config (see same link above).