Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Knowledge Base #211

Closed
wants to merge 5 commits into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 4 additions & 0 deletions build.js
Original file line number Diff line number Diff line change
Expand Up @@ -101,6 +101,10 @@ function buildlocale (source, locale) {
sortBy: 'date',
reverse: true,
refer: false
},
knowledgeBase: {
pattern: 'knowledge/**/*.md',
refer: false
}
}))
.use(markdown(markedOptions))
Expand Down
17 changes: 1 addition & 16 deletions layouts/docs.hbs
Original file line number Diff line number Diff line change
Expand Up @@ -8,22 +8,7 @@
<div id="main">
<div class="container has-side-nav">

<aside>
<ul>
<li{{#equals path site.docs.link}} class="active"{{/equals}}>
<a href="/{{site.locale}}/{{site.docs.link}}/">{{site.docs.text}}</a>
</li>
<li{{#equals path site.docs.es6.link}} class="active"{{/equals}}>
<a href="/{{site.locale}}/{{site.docs.es6.link}}/">{{site.docs.es6.text}}</a>
</li>
<li{{#equals path site.docs.faq.link}} class="active"{{/equals}}>
<a href="/{{site.locale}}/{{site.docs.faq.link}}/">{{site.docs.faq.text}}</a>
</li>
<li{{#equals path site.docs.api.link}} class="active"{{/equals}}>
<a href="{{site.docs.api.link}}">{{site.docs.api.text}}</a>
</li>
</ul>
</aside>
{{> docs-menu }}

<article>
{{{ contents }}}
Expand Down
26 changes: 26 additions & 0 deletions layouts/knowledge-base-index.hbs
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
<!DOCTYPE html>
<html lang="{{site.locale}}">
{{> html-head }}

<body>
{{> header }}

<div id="main">
<div class="container has-side-nav">

{{> docs-menu }}

<article>
{{{ contents }}}

{{#each collections.knowledgeBase}}
<li><a href="/{{../site.locale}}/{{ path }}/">{{ title }}</a></li>
{{/each}}
</article>

</div>
</div>

{{> footer }}
</body>
</html>
25 changes: 25 additions & 0 deletions layouts/knowledge-post.hbs
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
<!DOCTYPE html>
<html lang="{{site.locale}}">
{{> html-head }}

<body>
{{> header }}

<div id="main">
<div class="container">

<article>
<div class="blogpost-header">
<h1>{{title}}</h1>
<span class="blogpost-meta">{{#if author}}{{i18n site.by}} {{author}}, {{/if}}<time datetime="{{ date }}">{{ strftime date }}</time></span>
</div>

{{{ contents }}}
</article>

</div>
</div>

{{> footer }}
</body>
</html>
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
---
title: How to access query string parameters
date: '2011-08-26T10:08:50.000Z'
tags:
- http
difficulty: 1
layout: knowledge-post.hbs
---

In Node.js, functionality to aid in the accessing of URL query string parameters is built into the standard library. The built-in `url.parse` method takes care of most of the heavy lifting for us. Here is an example script using this handy function and an explanation on how it works:

var fs = require('fs');
var http = require('http');
var url = require('url') ;

http.createServer(function (req, res) {
var queryObject = url.parse(req.url,true).query;
console.log(queryObject);

res.writeHead(200);
res.end('Feel free to add query parameters to the end of the url');
}).listen(8080);

The key part of this whole script is this line: `var queryObject = url.parse(req.url,true).query;`. Let's take a look at things from the inside-out. First off, `req.url` will look like `/app.js?foo=bad&baz=foo`. This is the part that is in the URL bar of the browser. Next, it gets passed to `url.parse` which parses out the various elements of the URL (NOTE: the second paramater is a boolean stating whether the method should parse the query string, so we set it to true). Finally, we access the `.query` property, which returns us a nice, friendly Javascript object with our query string data.


95 changes: 95 additions & 0 deletions locale/en/knowledge/HTTP/clients/how-to-create-a-HTTP-request.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,95 @@
---
title: How do I make a http request?
date: '2011-08-26T10:08:50.000Z'
tags:
- core
- http
difficulty: 2
layout: knowledge-post.hbs
---


Another extremely common programming task is making an HTTP request to a web server. Node.js provides an extremely simple API for this functionality in the form of `http.request`.

As an example, we are going to preform a GET request to [www.random.org/integers/?num=1&min=1&max=10&col=1&base=10&format=plain&rnd=new](www.random.org/integers/?num=1&min=1&max=10&col=1&base=10&format=plain&rnd=new) (which returns a random integer between 1 and 10) and print the result to the console.

var http = require('http');

//The url we want is: 'www.random.org/integers/?num=1&min=1&max=10&col=1&base=10&format=plain&rnd=new'
var options = {
host: 'www.random.org',
path: '/integers/?num=1&min=1&max=10&col=1&base=10&format=plain&rnd=new'
};

callback = function(response) {
var str = '';

//another chunk of data has been recieved, so append it to `str`
response.on('data', function (chunk) {
str += chunk;
});

//the whole response has been recieved, so we just print it out here
response.on('end', function () {
console.log(str);
});
}

http.request(options, callback).end();


Making a POST request is just as easy. We will make a POST request to `www.nodejitsu.com:1337` which is running a server that will echo back what we post. The code for making a POST request is almost identical to making a GET request, just a few simple modifications:

var http = require('http');

//The url we want is `www.nodejitsu.com:1337/`
var options = {
host: 'www.nodejitsu.com',
path: '/',
//since we are listening on a custom port, we need to specify it by hand
port: '1337',
//This is what changes the request to a POST request
method: 'POST'
};

callback = function(response) {
var str = ''
response.on('data', function (chunk) {
str += chunk;
});

response.on('end', function () {
console.log(str);
});
}

var req = http.request(options, callback);
//This is the data we are posting, it needs to be a string or a buffer
req.write("hello world!");
req.end();

Throwing in custom headers is just a tiny bit harder. On `www.nodejitsu.com:1338` we are running a server that will print out the `custom` header. So we will just make a quick request to it:

var http = require('http');

var options = {
host: 'www.nodejitsu.com',
path: '/',
port: '1338',
//This is the only line that is new. `headers` is an object with the headers to request
headers: {'custom': 'Custom Header Demo works'}
};

callback = function(response) {
var str = ''
response.on('data', function (chunk) {
str += chunk;
});

response.on('end', function () {
console.log(str);
});
}

var req = http.request(options, callback);
req.end();
34 changes: 34 additions & 0 deletions locale/en/knowledge/HTTP/servers/how-to-create-a-HTTP-server.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
---
title: How do I create a HTTP server?
date: '2011-08-26T10:08:50.000Z'
tags:
- http
difficulty: 1
layout: knowledge-post.hbs
---


Making a simple HTTP server in Node.js has become the de facto 'hello world' for the platform. On the one hand, Node.js provides extremely easy-to-use HTTP APIs; on the other hand, a simple web server also serves as an excellent demonstration of Node's asynchronous strengths.

Let's take a look at a very simple example:

var http = require('http');
var requestListener = function (req, res) {
res.writeHead(200);
res.end('Hello, World!\n');
}

var server = http.createServer(requestListener);
server.listen(8080);

Save this in a file called `server.js` - run `node server.js`, and your program will hang there... it's waiting for connections to respond to, so you'll have to give it one if you want to see it do anything. Try opening up a browser, and typing `localhost:8080` into the location bar. If everything has been set up correctly, you should see your server saying hello!

Let's take a more in-depth look at what the above code is doing. First, a function is defined called `requestListener` that takes a request object and a response object as parameters.

The request object contains things such as the requested URL, but in this example we ignore it and always return "Hello World".

The response object is how we send the headers and contents of the response back to the user making the request. Here we return a 200 response code (signaling a successful response) with the body "Hello World". Other headers, such as `Content-type`, would also be set here.

Next, the `http.createServer` method creates a server that calls `requestListener` whenever a request comes in. The next line, `server.listen(8080)`, calls the `listen` method, which causes the server to wait for incoming requests on the specified port - 8080, in this case.

There you have it - your most basic Node.js HTTP server.
47 changes: 47 additions & 0 deletions locale/en/knowledge/HTTP/servers/how-to-create-a-HTTPS-server.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,47 @@
---
title: How to create an https server?
date: '2011-08-26T10:08:50.000Z'
tags:
- https
difficulty: 1
layout: knowledge-post.hbs
---

*If you're using [Nodejitsu](http://nodejitsu.com)*, we handle HTTPS for you. Free SSL on jit.su and nodejitsu.com subdomains, and SSL on custom domains for business customers.
*It's never necessary to create an HTTPS server yourself.*

- - -

To create an HTTPS server, you need two things: an SSL certificate, and Node's built-in `https` module.

We need to start out with a word about SSL certificates. Speaking generally, there are two kinds of certificates: those signed by a 'Certificate Authority', or CA, and 'self-signed certificates'. A Certificate Authority is a trusted source for an SSL certificate, and using a certificate from a CA allows your users to be trust the identity of your website. In most cases, you would want to use a CA-signed certificate in a production environment - for testing purposes, however, a self-signed certicate will do just fine.

To generate a self-signed certificate, run the following in your shell:

openssl genrsa -out key.pem
openssl req -new -key key.pem -out csr.pem
openssl x509 -req -days 9999 -in csr.pem -signkey key.pem -out cert.pem
rm csr.pem

This should leave you with two files, `cert.pem` (the certificate) and `key.pem` (the private key). This is all you need for a SSL connection. So now you set up a quick hello world example (the biggest difference between https and [http](/how-do-i-create-a-http-server) is the `options` parameter):

var https = require('https');
var fs = require('fs');

var options = {
key: fs.readFileSync('key.pem'),
cert: fs.readFileSync('cert.pem')
};

var a = https.createServer(options, function (req, res) {
res.writeHead(200);
res.end("hello world\n");
}).listen(8000);

NODE PRO TIP: Note `fs.readFileSync` - unlike `fs.readFile`, `fs.readFileSync` will block the entire process until it completes. In situations like this - loading vital configuration data - the `sync` functions are okay. In a busy server, however, using a synchronous function during a request will force the server to deal with the requests one by one!

Now that your server is set up and started, you should be able to get the file with curl:

curl -k https://localhost:8000

or in your browser, by going to https://localhost:8000 .
Original file line number Diff line number Diff line change
@@ -0,0 +1,63 @@
---
title: How to handle multipart form data
date: '2011-09-09T10:08:50.000Z'
tags:
- http
- forms
- multipart
- uploads
difficulty: 3
layout: knowledge-post.hbs
---

Handling form data and file uploads properly is an important and complex problem in HTTP servers. Doing it by hand would involve parsing streaming binary data, writing it to the file system, parsing out other form data, and several other complex concerns - luckily, only a very few people will need to worry about it on that deep level. Felix Geisendorfer, one of the Node.js core committers, wrote a library called `node-formidable` that handles all the hard parts for you. With its friendly API, you can be parsing forms and receiving file uploads in no time.

This example is taken directly from the `node-formidable` GitHub page, with some additional explanation added.

var formidable = require('formidable'),
http = require('http'),
util = require('util');

http.createServer(function(req, res) {

// This if statement is here to catch form submissions, and initiate multipart form data parsing.

if (req.url == '/upload' && req.method.toLowerCase() == 'post') {

// Instantiate a new formidable form for processing.

var form = new formidable.IncomingForm();

// form.parse analyzes the incoming stream data, picking apart the different fields and files for you.

form.parse(req, function(err, fields, files) {
if (err) {

// Check for and handle any errors here.

console.error(err.message);
return;
}
res.writeHead(200, {'content-type': 'text/plain'});
res.write('received upload:\n\n');

// This last line responds to the form submission with a list of the parsed data and files.

res.end(util.inspect({fields: fields, files: files}));
});
return;
}

// If this is a regular request, and not a form submission, then send the form.

res.writeHead(200, {'content-type': 'text/html'});
res.end(
'<form action="/upload" enctype="multipart/form-data" method="post">'+
'<input type="text" name="title"><br>'+
'<input type="file" name="upload" multiple="multiple"><br>'+
'<input type="submit" value="Upload">'+
'</form>'
);
}).listen(8080);

Try it out for yourself - it's definitely the simpler solution, and `node-formidable` is a battle-hardened, production-ready library. Let userland solve problems like this for you, so that you can get back to writing the rest of your code!
Loading