diff --git a/.markdownlint.json b/.markdownlint.json index d47ac8bcfd0a0..c104586b6e717 100644 --- a/.markdownlint.json +++ b/.markdownlint.json @@ -8,7 +8,6 @@ "MD024": false, "MD025": false, "MD026": false, - "MD027": false, "MD032": false, "MD033": { "allowed_elements": [ @@ -29,5 +28,7 @@ "MD036": false, "MD040": false, "MD041": false, - "MD046": false + "MD046": { + "style": "fenced" + } } diff --git a/locale/ar/docs/guides/anatomy-of-an-http-transaction.md b/locale/ar/docs/guides/anatomy-of-an-http-transaction.md index d57ad8c926330..26db956bf806f 100644 --- a/locale/ar/docs/guides/anatomy-of-an-http-transaction.md +++ b/locale/ar/docs/guides/anatomy-of-an-http-transaction.md @@ -309,8 +309,8 @@ http.createServer((request, response) => { ``` >**ملاحظة:** عند التحقق من الرابط URL بهذه الطريقة، نحن نقوم بشكل من التوجيه "routing". - ويوجد أشكال أخرى للتوجيه بسيطة مثل دالة `بَدَّالَةٌ` `switch` أو معقدة كما في أدوات مثل - [`express`][]. إذا كنت نبحث على شئ يقوم بالتوجيه ولاشئ أخر جرب [`router`][]. +ويوجد أشكال أخرى للتوجيه بسيطة مثل دالة `بَدَّالَةٌ` `switch` أو معقدة كما في أدوات مثل +[`express`][]. إذا كنت نبحث على شئ يقوم بالتوجيه ولاشئ أخر جرب [`router`][]. رائع! الآن نستقر على تبسيط هذا وتذكر كائنات الطلب `request` هي تدقف قابل للقراءة [`ReadableStream`][] و كائنات الجواب `response` هي تدفق قابل للكتابة [`WritableStream`][]. diff --git a/locale/en/blog/feature/streams2.md b/locale/en/blog/feature/streams2.md index 793617ec4a821..2118daeb46511 100644 --- a/locale/en/blog/feature/streams2.md +++ b/locale/en/blog/feature/streams2.md @@ -109,7 +109,7 @@ feedback. # Stream - Stability: 2 - Unstable +> Stability: 2 - Unstable A stream is an abstract interface implemented by various objects in Node. For example a request to an HTTP server is a stream, as is @@ -494,7 +494,9 @@ This function returns the `destination` stream. For example, emulating the Unix `cat` command: - process.stdin.pipe(process.stdout); +```javascript +process.stdin.pipe(process.stdout); +``` By default `end()` is called on the destination when the source stream emits `end`, so that `destination` is no longer writable. Pass `{ end: @@ -503,10 +505,12 @@ false }` as `options` to keep the destination stream open. This keeps `writer` open so that "Goodbye" can be written at the end. - reader.pipe(writer, { end: false }); - reader.on("end", function() { - writer.end("Goodbye\n"); - }); +```javascript +reader.pipe(writer, { end: false }); +reader.on("end", function() { + writer.end("Goodbye\n"); +}); +``` Note that `process.stderr` and `process.stdout` are never closed until the process exits, regardless of the specified options. diff --git a/locale/en/blog/release/v0.8.6.md b/locale/en/blog/release/v0.8.6.md index 441f872e4ea5c..6087785f7077e 100644 --- a/locale/en/blog/release/v0.8.6.md +++ b/locale/en/blog/release/v0.8.6.md @@ -14,8 +14,10 @@ supported Unix operating systems (Linux, Darwin, and SmartOS). To use the binary distribution tarballs, you can unpack them directly into a destination directory: - cd ~/node/ # or /usr/local if you're feeling brave - tar xzvf /path/to/binary.tar.gz --strip=1 +``` +cd ~/node/ # or /usr/local if you're feeling brave +tar xzvf /path/to/binary.tar.gz --strip=1 +``` This is an experimental feature. Please use it and provide feedback. diff --git a/locale/en/knowledge/HTTP/clients/how-to-create-a-HTTP-request.md b/locale/en/knowledge/HTTP/clients/how-to-create-a-HTTP-request.md index 8d00c0ae5ac6d..a8ab776e4e0a6 100644 --- a/locale/en/knowledge/HTTP/clients/how-to-create-a-HTTP-request.md +++ b/locale/en/knowledge/HTTP/clients/how-to-create-a-HTTP-request.md @@ -12,82 +12,88 @@ Another extremely common programming task is making an HTTP request to a web ser As an example, we are going to preform a GET request to (which returns a random integer between 1 and 10) and print the result to the console. - var http = require('http'); +```javascript +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' - }; +//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 = ''; +callback = function(response) { + var str = ''; - //another chunk of data has been received, so append it to `str` - response.on('data', function (chunk) { - str += chunk; - }); + //another chunk of data has been received, so append it to `str` + response.on('data', function (chunk) { + str += chunk; + }); - //the whole response has been received, so we just print it out here - response.on('end', function () { - console.log(str); - }); - } + //the whole response has been received, so we just print it out here + response.on('end', function () { + console.log(str); + }); +} - http.request(options, callback).end(); +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(); +```javascript +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(); +```javascript +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(); +``` diff --git a/locale/en/knowledge/HTTP/servers/how-to-create-a-HTTP-server.md b/locale/en/knowledge/HTTP/servers/how-to-create-a-HTTP-server.md index 309f15a5e748c..787c82424b111 100644 --- a/locale/en/knowledge/HTTP/servers/how-to-create-a-HTTP-server.md +++ b/locale/en/knowledge/HTTP/servers/how-to-create-a-HTTP-server.md @@ -11,15 +11,17 @@ Making a simple HTTP server in Node.js has become the de facto 'hello world' for Let's take a look at a very simple example: - const http = require('http'); +```javascript +const http = require('http'); - const requestListener = function (req, res) { - res.writeHead(200); - res.end('Hello, World!\n'); - } +const requestListener = function (req, res) { + res.writeHead(200); + res.end('Hello, World!\n'); +} - const server = http.createServer(requestListener); - server.listen(8080); +const 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! diff --git a/locale/en/knowledge/HTTP/servers/how-to-create-a-HTTPS-server.md b/locale/en/knowledge/HTTP/servers/how-to-create-a-HTTPS-server.md index 7e90edf8d4e6d..ca5a43c3735ea 100644 --- a/locale/en/knowledge/HTTP/servers/how-to-create-a-HTTPS-server.md +++ b/locale/en/knowledge/HTTP/servers/how-to-create-a-HTTPS-server.md @@ -18,25 +18,29 @@ We need to start out with a word about SSL certificates. Speaking generally, th 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 +``` +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). Put these files in the same directory as your Node.js server file. 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](/en/knowledge/HTTP/servers/how-to-create-a-HTTP-server/) is the `options` parameter): - const https = require('https'); - const fs = require('fs'); +```javascript +const https = require('https'); +const fs = require('fs'); - const options = { - key: fs.readFileSync('key.pem'), - cert: fs.readFileSync('cert.pem') - }; +const options = { + key: fs.readFileSync('key.pem'), + cert: fs.readFileSync('cert.pem') +}; - https.createServer(options, function (req, res) { - res.writeHead(200); - res.end("hello world\n"); - }).listen(8000); +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! @@ -44,6 +48,8 @@ NODE PRO TIP: Note `fs.readFileSync` - unlike `fs.readFile`, `fs.readFileSync` w Now that your server is set up and started, you should be able to get the file with curl: - curl -k https://localhost:8000 +``` +curl -k https://localhost:8000 +``` or in your browser, by going to https://localhost:8000 . diff --git a/locale/en/knowledge/HTTP/servers/how-to-handle-multipart-form-data.md b/locale/en/knowledge/HTTP/servers/how-to-handle-multipart-form-data.md index bba72f6901d83..cd67e8029b1ed 100644 --- a/locale/en/knowledge/HTTP/servers/how-to-handle-multipart-form-data.md +++ b/locale/en/knowledge/HTTP/servers/how-to-handle-multipart-form-data.md @@ -14,50 +14,52 @@ Handling form data and file uploads properly is an important and complex problem 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'); +```javascript +var formidable = require('formidable'), + http = require('http'), + util = require('util'); - http.createServer(function(req, res) { +http.createServer(function(req, res) { - // This if statement is here to catch form submissions, and initiate multipart form data parsing. + // This if statement is here to catch form submissions, and initiate multipart form data parsing. - if (req.url == '/upload' && req.method.toLowerCase() == 'post') { + if (req.url == '/upload' && req.method.toLowerCase() == 'post') { - // Instantiate a new formidable form for processing. + // Instantiate a new formidable form for processing. - var form = new formidable.IncomingForm(); + var form = new formidable.IncomingForm(); - // form.parse analyzes the incoming stream data, picking apart the different fields and files for you. + // 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) { + form.parse(req, function(err, fields, files) { + if (err) { - // Check for and handle any errors here. + // 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'); + 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. + // 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; - } + res.end(util.inspect({fields: fields, files: files})); + }); + return; + } - // If this is a regular request, and not a form submission, then send the form. + // If this is a regular request, and not a form submission, then send the form. - res.writeHead(200, {'content-type': 'text/html'}); - res.end( - '
'+ - '
'+ - '
'+ - ''+ - '
' - ); - }).listen(8080); + res.writeHead(200, {'content-type': 'text/html'}); + res.end( + '
'+ + '
'+ + '
'+ + ''+ + '
' + ); +}).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! diff --git a/locale/en/knowledge/HTTP/servers/how-to-read-POST-data.md b/locale/en/knowledge/HTTP/servers/how-to-read-POST-data.md index 51b66fcb0308d..12627ec3367a6 100644 --- a/locale/en/knowledge/HTTP/servers/how-to-read-POST-data.md +++ b/locale/en/knowledge/HTTP/servers/how-to-read-POST-data.md @@ -11,28 +11,30 @@ Reading the data from a POST request (i.e. a form submission) can be a little bi Here is a quick script that shows you how to do exactly that: - var http = require('http'); - var postHTML = - 'Post Example' + - '' + - '
' + - 'Input 1:
' + - 'Input 2:
' + - '' + - '
' + - ''; - - http.createServer(function (req, res) { - var body = ""; - req.on('data', function (chunk) { - body += chunk; - }); - req.on('end', function () { - console.log('POSTed: ' + body); - res.writeHead(200); - res.end(postHTML); - }); - }).listen(8080); +```javascript +var http = require('http'); +var postHTML = + 'Post Example' + + '' + + '
' + + 'Input 1:
' + + 'Input 2:
' + + '' + + '
' + + ''; + +http.createServer(function (req, res) { + var body = ""; + req.on('data', function (chunk) { + body += chunk; + }); + req.on('end', function () { + console.log('POSTed: ' + body); + res.writeHead(200); + res.end(postHTML); + }); +}).listen(8080); +``` The variable `postHTML` is a static string containing the HTML for two input boxes and a submit box - this HTML is provided so that you can `POST` example data. This is NOT the right way to serve static HTML - please see [How to Serve Static Files](/en/knowledge/HTTP/servers/how-to-serve-static-files/) for a more proper example. diff --git a/locale/en/knowledge/HTTP/servers/how-to-serve-static-files.md b/locale/en/knowledge/HTTP/servers/how-to-serve-static-files.md index ce43a36cd642c..003529e0abe86 100644 --- a/locale/en/knowledge/HTTP/servers/how-to-serve-static-files.md +++ b/locale/en/knowledge/HTTP/servers/how-to-serve-static-files.md @@ -9,20 +9,22 @@ layout: knowledge-post.hbs A basic necessity for most [http servers](/en/knowledge/HTTP/servers/how-to-create-a-HTTPS-server/) is to be able to serve static files. Thankfully, it is not that hard to do in Node.js. First you [read the file](/en/knowledge/file-system/how-to-read-files-in-nodejs/), then you serve the file. Here is an example of a script that will serve the files in the current directory: - var fs = require('fs'), - http = require('http'); - - http.createServer(function (req, res) { - fs.readFile(__dirname + req.url, function (err,data) { - if (err) { - res.writeHead(404); - res.end(JSON.stringify(err)); - return; - } - res.writeHead(200); - res.end(data); - }); - }).listen(8080); +```javascript +var fs = require('fs'), + http = require('http'); + +http.createServer(function (req, res) { + fs.readFile(__dirname + req.url, function (err,data) { + if (err) { + res.writeHead(404); + res.end(JSON.stringify(err)); + return; + } + res.writeHead(200); + res.end(data); + }); +}).listen(8080); +``` This example takes the path requested and it serves that path, relative to the local directory. This works fine as a quick solution; however, there are a few problems with this approach. First, this code does not correctly handle mime types. Additionally, a proper static file server should really be taking advantage of client side caching, and should send a "Not Modified" response if nothing has changed. Furthermore, there are security bugs that can enable a malicious user to break out of the current directory. (for example, `GET /../../../`). @@ -30,13 +32,15 @@ Each of these can be addressed invidually without much difficulty. You can send There is a good static file server called [node-static](https://github.com/cloudhead/node-static) written by Alexis Sellier which you can leverage. Here is a script which functions similarly to the previous one: - var static = require('node-static'); - var http = require('http'); +```javascript +var static = require('node-static'); +var http = require('http'); - var file = new(static.Server)(); +var file = new(static.Server)(); - http.createServer(function (req, res) { - file.serve(req, res); - }).listen(8080); +http.createServer(function (req, res) { + file.serve(req, res); +}).listen(8080); +``` This is a fully functional file server that doesn't have any of the bugs previously mentioned. This is just the most basic set up, there are more things you can do if you look at [the api](https://github.com/cloudhead/node-static). Also since it is an open source project, you can always modify it to your needs (and feel free to contribute back to the project!). diff --git a/locale/en/knowledge/advanced/buffers/how-to-use-buffers.md b/locale/en/knowledge/advanced/buffers/how-to-use-buffers.md index 05af947619173..a48e275becd42 100644 --- a/locale/en/knowledge/advanced/buffers/how-to-use-buffers.md +++ b/locale/en/knowledge/advanced/buffers/how-to-use-buffers.md @@ -61,19 +61,25 @@ This initializes the buffer to a binary encoding of the first string as specifie Given that there is already a buffer created: - > var buffer = new Buffer(16); +``` +> var buffer = new Buffer(16); +``` we can start writing strings to it: - > buffer.write("Hello", "utf-8") - 5 +``` +> buffer.write("Hello", "utf-8") +5 +``` The first argument to `buffer.write` is the string to write to the buffer, and the second argument is the string encoding. It happens to default to utf-8 so this argument is extraneous. `buffer.write` returned 5. This means that we wrote to five bytes of the buffer. The fact that the string "Hello" is also 5 characters long is coincidental, since each character *just happened* to be 8 bits apiece. This is useful if you want to complete the message: - > buffer.write(" world!", 5, "utf-8") - 7 +``` +> buffer.write(" world!", 5, "utf-8") +7 +``` When `buffer.write` has 3 arguments, the second argument indicates an offset, or the index of the buffer to start writing at. @@ -83,28 +89,34 @@ When `buffer.write` has 3 arguments, the second argument indicates an offset, or Probably the most common way to read buffers is to use the `toString` method, since many buffers contain text: - > buffer.toString('utf-8') - 'Hello world!\u0000�k\t' +``` +> buffer.toString('utf-8') +'Hello world!\u0000�k\t' +``` Again, the first argument is the encoding. In this case, it can be seen that not the entire buffer was used! Luckily, because we know how many bytes we've written to the buffer, we can simply add more arguments to "stringify" the slice that's actually interesting: - > buffer.toString("utf-8", 0, 12) - 'Hello world!' +``` +> buffer.toString("utf-8", 0, 12) +'Hello world!' +``` #### Individual octets: You can also set individual bytes by using an array-like syntax: - > buffer[12] = buffer[11]; - 33 - > buffer[13] = "1".charCodeAt(); - 49 - > buffer[14] = buffer[13]; - 49 - > buffer[15] = 33 - 33 - > buffer.toString("utf-8") - 'Hello world!!11!' +``` +> buffer[12] = buffer[11]; +33 +> buffer[13] = "1".charCodeAt(); +49 +> buffer[14] = buffer[13]; +49 +> buffer[15] = 33 +33 +> buffer.toString("utf-8") +'Hello world!!11!' +``` In this example, I set the remaining bytes, by hand, such that they represent utf-8 encoded "!" and "1" characters. @@ -118,11 +130,13 @@ This method checks to see if `object` is a buffer, similar to `Array.isArray`. With this function, you can check the number of bytes required to encode a string with a given encoding (which defaults to utf-8). This length is *not* the same as string length, since many characters require more bytes to encode. For example: - > var snowman = "☃"; - > snowman.length - 1 - > Buffer.byteLength(snowman) - 3 +``` +> var snowman = "☃"; +> snowman.length +1 +> Buffer.byteLength(snowman) +3 +``` The unicode snowman is only one character, but takes 3 entire bytes to encode! @@ -130,11 +144,13 @@ The unicode snowman is only one character, but takes 3 entire bytes to encode! This is the length of your buffer, and represents how much memory is allocated. It is not the same as the size of the buffer's contents, since a buffer may be half-filled. For example: - > var buffer = new Buffer(16) - > buffer.write(snowman) - 3 - > buffer.length - 16 +``` +> var buffer = new Buffer(16) +> buffer.write(snowman) +3 +> buffer.length +16 +``` In this example, the contents written to the buffer only consist of three groups (since they represent the single-character snowman), but the buffer's length is still 16, as it was initialized. @@ -142,14 +158,16 @@ In this example, the contents written to the buffer only consist of three groups `buffer.copy` allows one to copy the contents of one buffer onto another. The first argument is the target buffer on which to copy the contents of `buffer`, and the rest of the arguments allow for copying only a subsection of the source buffer to somewhere in the middle of the target buffer. For example: - > var frosty = new Buffer(24) - > var snowman = new Buffer("☃", "utf-8") - > frosty.write("Happy birthday! ", "utf-8") - 16 - > snowman.copy(frosty, 16) - 3 - > frosty.toString("utf-8", 0, 19) - 'Happy birthday! ☃' +``` +> var frosty = new Buffer(24) +> var snowman = new Buffer("☃", "utf-8") +> frosty.write("Happy birthday! ", "utf-8") +16 +> snowman.copy(frosty, 16) +3 +> frosty.toString("utf-8", 0, 19) +'Happy birthday! ☃' +``` In this example, I copied the "snowman" buffer, which contains a 3 byte long character, to the "frosty" buffer, to which I had written to the first 16 bytes. Because the snowman character is 3 bytes long, the result takes up 19 bytes of the buffer. @@ -157,12 +175,14 @@ In this example, I copied the "snowman" buffer, which contains a 3 byte long cha This method's API is generally the same as that of `Array.prototype.slice`, but with one very import difference: The slice is **not** a new buffer and merely references a subset of the memory space. *Modifying the slice will also modify the original buffer*! For example: - > var puddle = frosty.slice(16, 19) - > puddle.toString() - '☃' - > puddle.write("___") - 3 - > frosty.toString("utf-8", 0, 19) - 'Happy birthday! ___' +``` +> var puddle = frosty.slice(16, 19) +> puddle.toString() +'☃' +> puddle.write("___") +3 +> frosty.toString("utf-8", 0, 19) +'Happy birthday! ___' +``` Now Frosty has been turned into a puddle of underscores. Bummer. diff --git a/locale/en/knowledge/advanced/streams/how-to-use-fs-create-read-stream.md b/locale/en/knowledge/advanced/streams/how-to-use-fs-create-read-stream.md index db4464bad2168..de859af4e7681 100644 --- a/locale/en/knowledge/advanced/streams/how-to-use-fs-create-read-stream.md +++ b/locale/en/knowledge/advanced/streams/how-to-use-fs-create-read-stream.md @@ -11,24 +11,26 @@ layout: knowledge-post.hbs The function `fs.createReadStream()` allows you to open up a readable stream in a very simple manner. All you have to do is pass the path of the file to start streaming in. It turns out that the response (as well as the request) objects are streams. So we will use this fact to create a http server that streams the files to the client. Since the code is simple enough, it is pretty easy just to read through it and comment why each line is necessary. - var http = require('http'); - var fs = require('fs'); +```javascript +var http = require('http'); +var fs = require('fs'); - http.createServer(function(req, res) { - // The filename is simple the local directory and tacks on the requested url - var filename = __dirname+req.url; +http.createServer(function(req, res) { + // The filename is simple the local directory and tacks on the requested url + var filename = __dirname+req.url; - // This line opens the file as a readable stream - var readStream = fs.createReadStream(filename); + // This line opens the file as a readable stream + var readStream = fs.createReadStream(filename); - // This will wait until we know the readable stream is actually valid before piping - readStream.on('open', function () { - // This just pipes the read stream to the response object (which goes to the client) - readStream.pipe(res); - }); + // This will wait until we know the readable stream is actually valid before piping + readStream.on('open', function () { + // This just pipes the read stream to the response object (which goes to the client) + readStream.pipe(res); + }); - // This catches any errors that happen while creating the readable stream (usually invalid names) - readStream.on('error', function(err) { - res.end(err); - }); - }).listen(8080); + // This catches any errors that happen while creating the readable stream (usually invalid names) + readStream.on('error', function(err) { + res.end(err); + }); +}).listen(8080); +``` diff --git a/locale/en/knowledge/advanced/streams/how-to-use-fs-create-write-stream.md b/locale/en/knowledge/advanced/streams/how-to-use-fs-create-write-stream.md index 8c678f854fc76..207c3cd5c6050 100644 --- a/locale/en/knowledge/advanced/streams/how-to-use-fs-create-write-stream.md +++ b/locale/en/knowledge/advanced/streams/how-to-use-fs-create-write-stream.md @@ -11,24 +11,26 @@ layout: knowledge-post.hbs The function `fs.createWriteStream()` creates a writable stream in a very simple manner. After a call to `fs.createWriteStream` with the filepath, you have a writeable stream to work with. It turns out that the response (as well as the request) objects are streams. So we will stream the `POST` data to the file `output`. Since the code is simple enough, it is pretty easy just to read through it and comment why each line is necessary. - var http = require('http'); - var fs = require('fs'); +```javascript +var http = require('http'); +var fs = require('fs'); - http.createServer(function(req, res) { - // This opens up the writeable stream to `output` - var writeStream = fs.createWriteStream('./output'); +http.createServer(function(req, res) { + // This opens up the writeable stream to `output` + var writeStream = fs.createWriteStream('./output'); - // This pipes the POST data to the file - req.pipe(writeStream); + // This pipes the POST data to the file + req.pipe(writeStream); - // After all the data is saved, respond with a simple html form so they can post more data - req.on('end', function () { - res.writeHead(200, {"content-type":"text/html"}); - res.end('
'); - }); + // After all the data is saved, respond with a simple html form so they can post more data + req.on('end', function () { + res.writeHead(200, {"content-type":"text/html"}); + res.end('
'); + }); - // This is here incase any errors occur - writeStream.on('error', function (err) { - console.log(err); - }); - }).listen(8080); + // This is here incase any errors occur + writeStream.on('error', function (err) { + console.log(err); + }); +}).listen(8080); +``` diff --git a/locale/en/knowledge/advanced/streams/how-to-use-stream-pipe.md b/locale/en/knowledge/advanced/streams/how-to-use-stream-pipe.md index 8afdfccef5100..7092389662ddf 100644 --- a/locale/en/knowledge/advanced/streams/how-to-use-stream-pipe.md +++ b/locale/en/knowledge/advanced/streams/how-to-use-stream-pipe.md @@ -12,76 +12,82 @@ If you've been using node.js for a while, you've definitely run into streams. H Streams make for quite a handy abstraction, and there's a lot you can do with them - as an example, let's take a look at stream.pipe, the method used to take a readable stream and connect it to a writeable steam. Suppose we wanted to spawn a `node` child process and pipe our stdout and stdin to its corresponding stdout and stdin. - #!/usr/bin/env node +```javascript +#!/usr/bin/env node - var child = require('child_process'); +var child = require('child_process'); - var myREPL = child.spawn('node'); +var myREPL = child.spawn('node'); - myREPL.stdout.pipe(process.stdout, { end: false }); +myREPL.stdout.pipe(process.stdout, { end: false }); - process.stdin.resume(); +process.stdin.resume(); - process.stdin.pipe(myREPL.stdin, { end: false }); +process.stdin.pipe(myREPL.stdin, { end: false }); - myREPL.stdin.on('end', function() { - process.stdout.write('REPL stream ended.'); - }); +myREPL.stdin.on('end', function() { + process.stdout.write('REPL stream ended.'); +}); - myREPL.on('exit', function (code) { - process.exit(code); - }); +myREPL.on('exit', function (code) { + process.exit(code); +}); +``` There you have it - spawn the node REPL as a child process, and pipe your stdin and stdout to its stdin and stdout. Make sure to listen for the child's 'exit' event, too, or else your program will just hang there when the REPL exits. Another use for stream.pipe is file streams. In node.js, fs.createReadStream and fs.createWriteStream are used to create a stream to an open file descriptor. Now let's look at how one might use stream.pipe to write to a file. You'll probably recognize most of the code: - #!/usr/bin/env node +```javascript +#!/usr/bin/env node - var child = require('child_process'), - fs = require('fs'); +var child = require('child_process'), + fs = require('fs'); - var myREPL = child.spawn('node'), - myFile = fs.createWriteStream('myOutput.txt'); +var myREPL = child.spawn('node'), + myFile = fs.createWriteStream('myOutput.txt'); - myREPL.stdout.pipe(process.stdout, { end: false }); - myREPL.stdout.pipe(myFile); +myREPL.stdout.pipe(process.stdout, { end: false }); +myREPL.stdout.pipe(myFile); - process.stdin.resume(); +process.stdin.resume(); - process.stdin.pipe(myREPL.stdin, { end: false }); - process.stdin.pipe(myFile); +process.stdin.pipe(myREPL.stdin, { end: false }); +process.stdin.pipe(myFile); - myREPL.stdin.on("end", function() { - process.stdout.write("REPL stream ended."); - }); +myREPL.stdin.on("end", function() { + process.stdout.write("REPL stream ended."); +}); - myREPL.on('exit', function (code) { - process.exit(code); - }); +myREPL.on('exit', function (code) { + process.exit(code); +}); +``` With those small additions, your stdin and the stdout from your REPL will both be piped to the writeable file stream you opened to 'myOutput.txt'. It's that simple - you can pipe streams to as many places as you want. Another very important use case for stream.pipe is with HTTP request and response objects. Here we have the very simplest kind of proxy: - #!/usr/bin/env node - - var http = require('http'); - - http.createServer(function(request, response) { - var proxy = http.createClient(9000, 'localhost') - var proxyRequest = proxy.request(request.method, request.url, request.headers); - proxyRequest.on('response', function (proxyResponse) { - proxyResponse.pipe(response); - }); - request.pipe(proxyRequest); - }).listen(8080); - - http.createServer(function (req, res) { - res.writeHead(200, { 'Content-Type': 'text/plain' }); - res.write('request successfully proxied to port 9000!' + '\n' + JSON.stringify(req.headers, true, 2)); - res.end(); - }).listen(9000); +```javascript +#!/usr/bin/env node + +var http = require('http'); + +http.createServer(function(request, response) { + var proxy = http.createClient(9000, 'localhost') + var proxyRequest = proxy.request(request.method, request.url, request.headers); + proxyRequest.on('response', function (proxyResponse) { + proxyResponse.pipe(response); + }); + request.pipe(proxyRequest); +}).listen(8080); + +http.createServer(function (req, res) { + res.writeHead(200, { 'Content-Type': 'text/plain' }); + res.write('request successfully proxied to port 9000!' + '\n' + JSON.stringify(req.headers, true, 2)); + res.end(); +}).listen(9000); +``` One could also use stream.pipe to send incoming requests to a file for logging, or to a child process, or any one of a number of other things. diff --git a/locale/en/knowledge/advanced/streams/what-are-streams.md b/locale/en/knowledge/advanced/streams/what-are-streams.md index 6368b4bf85606..c7b3732da80b0 100644 --- a/locale/en/knowledge/advanced/streams/what-are-streams.md +++ b/locale/en/knowledge/advanced/streams/what-are-streams.md @@ -16,27 +16,29 @@ As a quick example, we can write a simple version of `cp` (the unix utility that Run this script with arguments like `node cp.js src.txt dest.txt`. This would mean, in the code below, that `process.argv[2]` is `src.txt` and `process.argv[3]` is `desc.txt`. - var fs = require('fs'); - console.log(process.argv[2], '->', process.argv[3]); - - var readStream = fs.createReadStream(process.argv[2]); - var writeStream = fs.createWriteStream(process.argv[3]); - - readStream.on('data', function (chunk) { - writeStream.write(chunk); - }); - - readStream.on('end', function () { - writeStream.end(); - }); - - //Some basic error handling - readStream.on('error', function (err) { - console.log("ERROR", err); - }); - - writeStream.on('error', function (err) { - console.log("ERROR", err); - }); +```javascript +var fs = require('fs'); +console.log(process.argv[2], '->', process.argv[3]); + +var readStream = fs.createReadStream(process.argv[2]); +var writeStream = fs.createWriteStream(process.argv[3]); + +readStream.on('data', function (chunk) { + writeStream.write(chunk); +}); + +readStream.on('end', function () { + writeStream.end(); +}); + +//Some basic error handling +readStream.on('error', function (err) { + console.log("ERROR", err); +}); + +writeStream.on('error', function (err) { + console.log("ERROR", err); +}); +``` This sets up a readable stream from the source file and a writable stream to the destination file. Then whenever the readable stream gets data, it gets written to the writeable stream. Then finally it closes the writable stream when the readable stream is finished. NOTE: it would have been better to use [pipe](/en/knowledge/advanced/streams/how-to-use-stream-pipe/) like `readStream.pipe(writeStream);`, however, to show how streams work, we have done things the long way. diff --git a/locale/en/knowledge/cryptography/how-to-use-the-tls-module.md b/locale/en/knowledge/cryptography/how-to-use-the-tls-module.md index 75fd666e9d7ef..91e377422e9d9 100644 --- a/locale/en/knowledge/cryptography/how-to-use-the-tls-module.md +++ b/locale/en/knowledge/cryptography/how-to-use-the-tls-module.md @@ -30,26 +30,28 @@ TLS support in node is relatively new. The first stable version of node.js to su In most ways, the tls module's server api is similar to that of the net module. Besides the fact that it's for encrypted connections, the major difference is that the options object passed to `tls.connect` or `tls.createServer` needs to include information on both the private key and the certificate, in [pem format](https://en.wikipedia.org/wiki/X.509#Certificate_filename_extensions). Here's an example of a tls server: - var tls = require('tls'), - fs = require('fs'), - colors = require('colors'), - msg = [ - ".-..-..-. .-. .-. .--. .---. .-. .---. .-.", - ": :; :: : : :.-.: :: ,. :: .; :: : : . :: :", - ": :: : : :: :: :: :: :: .': : : :: :: :", - ": :: :: : : `' `' ;: :; :: :.`.: :__ : :; ::_;", - ":_;:_;:_; `.,`.,' `.__.':_;:_;:___.':___.':_;" - ].join("\n").cyan; - - var options = { - key: fs.readFileSync('private-key.pem'), - cert: fs.readFileSync('public-cert.pem') - }; - - tls.createServer(options, function (s) { - s.write(msg+"\n"); - s.pipe(s); - }).listen(8000); +```javascript +var tls = require('tls'), + fs = require('fs'), + colors = require('colors'), + msg = [ + ".-..-..-. .-. .-. .--. .---. .-. .---. .-.", + ": :; :: : : :.-.: :: ,. :: .; :: : : . :: :", + ": :: : : :: :: :: :: :: .': : : :: :: :", + ": :: :: : : `' `' ;: :; :: :.`.: :__ : :; ::_;", + ":_;:_;:_; `.,`.,' `.__.':_;:_;:___.':___.':_;" + ].join("\n").cyan; + +var options = { + key: fs.readFileSync('private-key.pem'), + cert: fs.readFileSync('public-cert.pem') +}; + +tls.createServer(options, function (s) { + s.write(msg+"\n"); + s.pipe(s); +}).listen(8000); +``` In this example, a "hello world" tls server is created, listening on port 8000. The options object includes two properties: `key` and `cert`. The contents of these properties come directly from the private key and public certificate stored on the filesystem. In this case they are binary buffers, but the tls module can also accept unicode strings. @@ -59,45 +61,51 @@ In order for this example server to work, of course, you will need a private key First, generate a private key: - $ openssl genrsa -out private-key.pem 1024 - Generating RSA private key, 1024 bit long modulus - ......................................++++++ - ........++++++ - e is 65537 (0x10001) +``` +$ openssl genrsa -out private-key.pem 1024 +Generating RSA private key, 1024 bit long modulus +......................................++++++ +........++++++ +e is 65537 (0x10001) +``` This creates a suitable private key and writes it to `./private-key.pem`. Next, create a Certificate Signing Request file using your private key: - $ openssl req -new -key private-key.pem -out csr.pem - You are about to be asked to enter information that will be incorporated - into your certificate request. - What you are about to enter is what is called a Distinguished Name or a DN. - There are quite a few fields but you can leave some blank - For some fields there will be a default value, - If you enter '.', the field will be left blank. - ----- - Country Name (2 letter code) [AU]:US - State or Province Name (full name) [Some-State]:California - Locality Name (eg, city) []:Oakland - Organization Name (eg, company) [Internet Widgits Pty Ltd]:Panco, Inc. - Organizational Unit Name (eg, section) []: - Common Name (eg, YOUR name) []:Joshua Holbrook - Email Address []:josh.holbrook@gmail.com - - Please enter the following 'extra' attributes - to be sent with your certificate request - A challenge password []:dangerface - An optional company name []: +``` +$ openssl req -new -key private-key.pem -out csr.pem +You are about to be asked to enter information that will be incorporated +into your certificate request. +What you are about to enter is what is called a Distinguished Name or a DN. +There are quite a few fields but you can leave some blank +For some fields there will be a default value, +If you enter '.', the field will be left blank. +----- +Country Name (2 letter code) [AU]:US +State or Province Name (full name) [Some-State]:California +Locality Name (eg, city) []:Oakland +Organization Name (eg, company) [Internet Widgits Pty Ltd]:Panco, Inc. +Organizational Unit Name (eg, section) []: +Common Name (eg, YOUR name) []:Joshua Holbrook +Email Address []:josh.holbrook@gmail.com + +Please enter the following 'extra' attributes +to be sent with your certificate request +A challenge password []:dangerface +An optional company name []: +``` The purpose of this CSR is to "request" a certificate. That is, if you wanted a CA to sign your certificate, you could give this file to them to process and they would give you back a certificate. Alternately, however, you may self-sign your certificate, again using your private key: - $ openssl x509 -req -in csr.pem -signkey private-key.pem -out public-cert.pem - Signature ok - subject=/C=US/ST=California/L=Oakland/O=Panco, Inc./CN=Joshua Holbrook/emailAddress=josh.holbrook@gmail.com - Getting Private key +``` +$ openssl x509 -req -in csr.pem -signkey private-key.pem -out public-cert.pem +Signature ok +subject=/C=US/ST=California/L=Oakland/O=Panco, Inc./CN=Joshua Holbrook/emailAddress=josh.holbrook@gmail.com +Getting Private key +``` This generates your certificate. Now you're cooking! @@ -105,7 +113,9 @@ This generates your certificate. Now you're cooking! One way to test out your new "hello world" server is to again use OpenSSL: - openssl s_client -connect 127.0.0.1:8000 +``` +openssl s_client -connect 127.0.0.1:8000 +``` You should see a bunch of output regarding the handshaking process, and then at the very end you should see a big, cyan figlet banner saying, "Hi world!" @@ -113,27 +123,29 @@ You should see a bunch of output regarding the handshaking process, and then at The tls module also supplies tools for connecting to such a server: - var tls = require('tls'), - fs = require('fs'); - - var options = { - key: fs.readFileSync('private-key.pem'), - cert: fs.readFileSync('public-cert.pem') - }; - - var conn = tls.connect(8000, options, function() { - if (conn.authorized) { - console.log("Connection authorized by a Certificate Authority."); - } else { - console.log("Connection not authorized: " + conn.authorizationError) - } - console.log(); - }); - - conn.on("data", function (data) { - console.log(data.toString()); - conn.end(); - }); +```javascript +var tls = require('tls'), + fs = require('fs'); + +var options = { + key: fs.readFileSync('private-key.pem'), + cert: fs.readFileSync('public-cert.pem') +}; + +var conn = tls.connect(8000, options, function() { + if (conn.authorized) { + console.log("Connection authorized by a Certificate Authority."); + } else { + console.log("Connection not authorized: " + conn.authorizationError) + } + console.log(); +}); + +conn.on("data", function (data) { + console.log(data.toString()); + conn.end(); +}); +``` The idea is similar, except instead of creating a server, this script connects to one instead. `tls.connect` also takes an options object, but then returns a stream. @@ -141,14 +153,16 @@ The idea is similar, except instead of creating a server, this script connects t This is what happens when the client is ran (with the server running): - $ node client.js - Connection not authorized: DEPTH_ZERO_SELF_SIGNED_CERT +``` +$ node client.js +Connection not authorized: DEPTH_ZERO_SELF_SIGNED_CERT - .-..-..-. .-. .-. .--. .---. .-. .---. .-. - : :; :: : : :.-.: :: ,. :: .; :: : : . :: : - : :: : : :: :: :: :: :: .': : : :: :: : - : :: :: : : `' `' ;: :; :: :.`.: :__ : :; ::_; - :_;:_;:_; `.,`.,' `.__.':_;:_;:___.':___.':_; +.-..-..-. .-. .-. .--. .---. .-. .---. .-. +: :; :: : : :.-.: :: ,. :: .; :: : : . :: : +: :: : : :: :: :: :: :: .': : : :: :: : +: :: :: : : `' `' ;: :; :: :.`.: :__ : :; ::_; +:_;:_;:_; `.,`.,' `.__.':_;:_;:___.':___.':_; +``` Note that self-signing the server certificate results in a non-authorized status because you're not listed as a trusted certificate authority. diff --git a/locale/en/knowledge/errors/what-are-the-error-conventions.md b/locale/en/knowledge/errors/what-are-the-error-conventions.md index 9fd1a0666c4d2..8399ada6aa683 100644 --- a/locale/en/knowledge/errors/what-are-the-error-conventions.md +++ b/locale/en/knowledge/errors/what-are-the-error-conventions.md @@ -12,34 +12,38 @@ In node.js, it is considered standard practice to handle errors in asynchronous It's simpler than it sounds; let's demonstrate. - var isTrue = function(value, callback) { - if (value === true) { - callback(null, "Value was true."); - } - else { - callback(new Error("Value is not true!")); - } - } - - var callback = function (error, retval) { - if (error) { - console.log(error); - return; - } - console.log(retval); - } - - // Note: when calling the same asynchronous function twice like this, you are in a race condition. - // You have no way of knowing for certain which callback will be called first when calling the functions in this manner. - - isTrue(false, callback); - isTrue(true, callback); - - { stack: [Getter/Setter], - arguments: undefined, - type: undefined, - message: 'Value is not true!' } - Value was true. +```javascript +var isTrue = function(value, callback) { + if (value === true) { + callback(null, "Value was true."); + } + else { + callback(new Error("Value is not true!")); + } +} + +var callback = function (error, retval) { + if (error) { + console.log(error); + return; + } + console.log(retval); +} + +// Note: when calling the same asynchronous function twice like this, you are in a race condition. +// You have no way of knowing for certain which callback will be called first when calling the functions in this manner. + +isTrue(false, callback); +isTrue(true, callback); +``` + +``` +{ stack: [Getter/Setter], + arguments: undefined, + type: undefined, + message: 'Value is not true!' } +Value was true. +``` As you can see from the example, the callback is called with null as its first argument if there is no error. However, if there is an error, you create an `Error` object, which then becomes the callback's only parameter. diff --git a/locale/en/knowledge/errors/what-is-the-error-object.md b/locale/en/knowledge/errors/what-is-the-error-object.md index 599e556495d16..e2802f837993e 100644 --- a/locale/en/knowledge/errors/what-is-the-error-object.md +++ b/locale/en/knowledge/errors/what-is-the-error-object.md @@ -12,31 +12,37 @@ The error object is a built-in object that provides a standard set of useful inf Code: - var error = new Error("The error message"); - console.log(error); - console.log(error.stack); +```javascript +var error = new Error("The error message"); +console.log(error); +console.log(error.stack); +``` Result: - { stack: [Getter/Setter], - arguments: undefined, - type: undefined, - message: 'The error message' } - Error: The error message - at Object. (/home/nico/example.js:1:75) - at Module._compile (module.js:407:26) - at Object..js (module.js:413:10) - at Module.load (module.js:339:31) - at Function._load (module.js:298:12) - at Array.0 (module.js:426:10) - at EventEmitter._tickCallback (node.js:126:26) +``` +{ stack: [Getter/Setter], + arguments: undefined, + type: undefined, + message: 'The error message' } +Error: The error message + at Object. (/home/nico/example.js:1:75) + at Module._compile (module.js:407:26) + at Object..js (module.js:413:10) + at Module.load (module.js:339:31) + at Function._load (module.js:298:12) + at Array.0 (module.js:426:10) + at EventEmitter._tickCallback (node.js:126:26) +``` `error.stack` shows you where an error came from, as well as a list of the function calls that preceded it - for your convenience, `error.stack` always prints `error.message` as the first line of its output, making `error.stack` a convenient single property to log during debugging. If you want to add more information to the Error object, you can always add properties, just as with any other JavaScript object: - var error = new Error("The error message"); - error.http_code = 404; - console.log(error); +```javascript +var error = new Error("The error message"); +error.http_code = 404; +console.log(error); +``` For more details how to use the Error object, check out the [article on error conventions](/en/knowledge/errors/what-are-the-error-conventions/) diff --git a/locale/en/knowledge/errors/what-is-try-catch.md b/locale/en/knowledge/errors/what-is-try-catch.md index b4f34d9c22228..c1b865f75abe1 100644 --- a/locale/en/knowledge/errors/what-is-try-catch.md +++ b/locale/en/knowledge/errors/what-is-try-catch.md @@ -10,33 +10,37 @@ layout: knowledge-post.hbs Example: - console.log("entering try-catch statement"); - - try { - console.log("entering try block"); - throw "thrown message"; - console.log("this message is never seen"); - } - catch (e) { - console.log("entering catch block"); - console.log(e); - console.log("leaving catch block"); - } - finally { - console.log("entering and leaving the finally block"); - } - - console.log("leaving try-catch statement"); +```javascript +console.log("entering try-catch statement"); + +try { + console.log("entering try block"); + throw "thrown message"; + console.log("this message is never seen"); +} +catch (e) { + console.log("entering catch block"); + console.log(e); + console.log("leaving catch block"); +} +finally { + console.log("entering and leaving the finally block"); +} + +console.log("leaving try-catch statement"); +``` Results: - entering try-catch statement - entering try block - entering catch block - thrown message - leaving catch block - entering and leaving the finally block - leaving try-catch statement +``` +entering try-catch statement +entering try block +entering catch block +thrown message +leaving catch block +entering and leaving the finally block +leaving try-catch statement +``` JavaScript's `try-catch-finally` statement works very similarly to the `try-catch-finally` encountered in C++ and Java. First, the try block is executed until and unless the code in it throws an exception (whether it is an explicit `throw` statement, the code has an uncaught native exception, or if the code calls a function that uses `throw`). diff --git a/locale/en/knowledge/file-system/how-to-read-files-in-nodejs.md b/locale/en/knowledge/file-system/how-to-read-files-in-nodejs.md index 1c7fc7fd8d00f..cff436d8013e9 100644 --- a/locale/en/knowledge/file-system/how-to-read-files-in-nodejs.md +++ b/locale/en/knowledge/file-system/how-to-read-files-in-nodejs.md @@ -9,10 +9,12 @@ layout: knowledge-post.hbs Reading the contents of a file into memory is a very common programming task, and, as with many other things, the Node.js core API provides methods to make this trivial. There are a variety of file system methods, all contained in the `fs` module. The easiest way to read the entire contents of a file is with `fs.readFile`, as follows: - fs = require('fs'); - fs.readFile(file, [encoding], [callback]); +```javascript +fs = require('fs'); +fs.readFile(file, [encoding], [callback]); - // file = (string) filepath of the file to read +// file = (string) filepath of the file to read +``` `encoding` is an optional parameter that specifies the type of encoding to read the file. Possible encodings are 'ascii', 'utf8', and 'base64'. If no encoding is provided, the default is `null`. @@ -20,34 +22,40 @@ Reading the contents of a file into memory is a very common programming task, an So if we wanted to read `/etc/hosts` and print it to stdout (just like UNIX `cat`): - fs = require('fs') - fs.readFile('/etc/hosts', 'utf8', function (err,data) { - if (err) { - return console.log(err); - } - console.log(data); - }); +```javascript +fs = require('fs') +fs.readFile('/etc/hosts', 'utf8', function (err,data) { + if (err) { + return console.log(err); + } + console.log(data); +}); +``` The contents of `/etc/hosts` should now be visible to you, provided you have permission to read the file in the first place. Let's now take a look at an example of what happens when you try to read an invalid file - the easiest example is one that doesn't exist. - fs = require('fs'); - fs.readFile('/doesnt/exist', 'utf8', function (err,data) { - if (err) { - return console.log(err); - } - console.log(data); - }); +```javascript +fs = require('fs'); +fs.readFile('/doesnt/exist', 'utf8', function (err,data) { + if (err) { + return console.log(err); + } + console.log(data); +}); +``` This is the output: - { stack: [Getter/Setter], - arguments: undefined, - type: undefined, - message: 'ENOENT, No such file or directory \'/doesnt/exist\'', - errno: 2, - code: 'ENOENT', - path: '/doesnt/exist' } +``` +{ stack: [Getter/Setter], + arguments: undefined, + type: undefined, + message: 'ENOENT, No such file or directory \'/doesnt/exist\'', + errno: 2, + code: 'ENOENT', + path: '/doesnt/exist' } +``` This is a basic Node.js [Error object](/en/knowledge/errors/what-is-the-error-object/) - it can often be useful to log `err.stack` directly, since this contains a stack trace to the location in code at which the Error object was created. diff --git a/locale/en/knowledge/file-system/how-to-search-files-and-directories-in-nodejs.md b/locale/en/knowledge/file-system/how-to-search-files-and-directories-in-nodejs.md index 3cefb24c47237..746c517b99162 100644 --- a/locale/en/knowledge/file-system/how-to-search-files-and-directories-in-nodejs.md +++ b/locale/en/knowledge/file-system/how-to-search-files-and-directories-in-nodejs.md @@ -9,33 +9,39 @@ layout: knowledge-post.hbs Suppose you want to list all the files in the current directory. One approach is to use the builtin `fs.readdir` [method](/en/knowledge/file-system/how-to-read-files-in-nodejs/). This will get you an array of all the files and directories on the specified path: - fs = require('fs'); - - fs.readdir(process.cwd(), function (err, files) { - if (err) { - console.log(err); - return; - } - console.log(files); - }); +```javascript +fs = require('fs'); + +fs.readdir(process.cwd(), function (err, files) { + if (err) { + console.log(err); + return; + } + console.log(files); +}); +``` Unfortunately, if you want to do a recursive list of files, then things get much more complicated very quickly. To avoid all of this scary complexity, this is one of the places where a Node.js user-land library can save the day. [Node-findit](https://github.com/substack/node-findit), by SubStack, is a helper module to make searching for files easier. It has interfaces to let you work with callbacks, events, or just plain old synchronously (not a good idea most of the time). To install `node-findit`, simply use npm: - npm install findit +``` +npm install findit +``` In the same folder, create a file called `example.js`, and then add this code. Run it with `node example.js`. This example uses the `node-findit` event-based interface. - //This sets up the file finder - var finder = require('findit').find(__dirname); +```javascript +//This sets up the file finder +var finder = require('findit').find(__dirname); - //This listens for directories found - finder.on('directory', function (dir) { - console.log('Directory: ' + dir + '/'); - }); +//This listens for directories found +finder.on('directory', function (dir) { + console.log('Directory: ' + dir + '/'); +}); - //This listens for files found - finder.on('file', function (file) { - console.log('File: ' + file); - }); +//This listens for files found +finder.on('file', function (file) { + console.log('File: ' + file); +}); +``` diff --git a/locale/en/knowledge/file-system/how-to-store-local-config-data.md b/locale/en/knowledge/file-system/how-to-store-local-config-data.md index 789474a9be5b5..59b6876a47559 100644 --- a/locale/en/knowledge/file-system/how-to-store-local-config-data.md +++ b/locale/en/knowledge/file-system/how-to-store-local-config-data.md @@ -12,43 +12,47 @@ Storing your Node.js application's configuration data is quite simple - every ob Let's take a look at a very simple (and contrived) example. First, to save some very simple data: - var fs = require('fs'); - - var myOptions = { - name: 'Avian', - dessert: 'cake' - flavor: 'chocolate', - beverage: 'coffee' - }; - - var data = JSON.stringify(myOptions); - - fs.writeFile('./config.json', data, function (err) { - if (err) { - console.log('There has been an error saving your configuration data.'); - console.log(err.message); - return; - } - console.log('Configuration saved successfully.') - }); +```javascript +var fs = require('fs'); + +var myOptions = { + name: 'Avian', + dessert: 'cake' + flavor: 'chocolate', + beverage: 'coffee' +}; + +var data = JSON.stringify(myOptions); + +fs.writeFile('./config.json', data, function (err) { + if (err) { + console.log('There has been an error saving your configuration data.'); + console.log(err.message); + return; + } + console.log('Configuration saved successfully.') +}); +``` It's really that simple - just `JSON.stringify()` and then save it however you'd like. Now let's load some configuration data: - var fs = require('fs'); +```javascript +var fs = require('fs'); - var data = fs.readFileSync('./config.json'), - myObj; +var data = fs.readFileSync('./config.json'), + myObj; - try { - myObj = JSON.parse(data); - console.dir(myObj); - } - catch (err) { - console.log('There has been an error parsing your JSON.') - console.log(err); - } +try { + myObj = JSON.parse(data); + console.dir(myObj); +} +catch (err) { + console.log('There has been an error parsing your JSON.') + console.log(err); +} +``` NODE PRO TIP: Even if you don't like using `try/catch`, this is a place to use it. `JSON.parse` is a very strict JSON parser, and errors are common - most importantly, though, `JSON.parse` uses the `throw` statement rather than giving a callback, so `try/catch` is the only way to guard against the error. @@ -56,27 +60,31 @@ Using the built-in `JSON` methods can take you far, but as with so many other pr Let's take a look now at how we'd perform some local configuration access with `nconf`. First, you'll need to install it to your project's working directory: - npm install nconf +``` +npm install nconf +``` After that, the syntax is a breeze. Have a look at an example: - var nconf = require('nconf'); - - nconf.use('file', { file: './config.json' }); - nconf.load(); - nconf.set('name', 'Avian'); - nconf.set('dessert:name', 'Ice Cream'); - nconf.set('dessert:flavor', 'chocolate'); - - console.log(nconf.get('dessert')); - - nconf.save(function (err) { - if (err) { - console.error(err.message); - return; - } - console.log('Configuration saved successfully.'); - }); +```javascript +var nconf = require('nconf'); + +nconf.use('file', { file: './config.json' }); +nconf.load(); +nconf.set('name', 'Avian'); +nconf.set('dessert:name', 'Ice Cream'); +nconf.set('dessert:flavor', 'chocolate'); + +console.log(nconf.get('dessert')); + +nconf.save(function (err) { + if (err) { + console.error(err.message); + return; + } + console.log('Configuration saved successfully.'); +}); +``` The only tricky thing to notice here is the delimiter - ':'. When accessing nested properties with `nconf`, a colon is used to delimit the namespaces of key names. If a specific sub-key is not provided, the whole object is set or returned. diff --git a/locale/en/knowledge/file-system/how-to-use-the-path-module.md b/locale/en/knowledge/file-system/how-to-use-the-path-module.md index 0684d311d9080..420ddc09acba2 100644 --- a/locale/en/knowledge/file-system/how-to-use-the-path-module.md +++ b/locale/en/knowledge/file-system/how-to-use-the-path-module.md @@ -12,44 +12,55 @@ The path module contains several helper functions to help make path manipulation The first function worth mentioning is `path.normalize`. This function takes a path (in the form of a string) and strips it of duplicate slashes and normalizes directory abbreviations, like '.' for 'this directory' and '..' for 'one level up'. For example: - > var path = require('path'); - > path.normalize('/a/.///b/d/../c/') - '/a/b/c/' +``` +> var path = require('path'); +> path.normalize('/a/.///b/d/../c/') +'/a/b/c/' +``` A closely related function to `normalize` is `join`. This function takes a variable number of arguments, joins them together, and normalizes the path. - > var path = require('path'); - > path.join('/a/.', './//b/', 'd/../c/') - '/a/b/c' +``` +> var path = require('path'); +> path.join('/a/.', './//b/', 'd/../c/') +'/a/b/c' +``` A possible use of `join` is to manipulate paths when serving urls: - > var path = require('path'); - > var url = '/index.html'; - > path.join(process.cwd(), 'static', url); - '/home/nico/static/index.html' +``` +> var path = require('path'); +> var url = '/index.html'; +> path.join(process.cwd(), 'static', url); +'/home/nico/static/index.html' +``` There are three functions which are used to extract the various parts of the path name: `basename`, `extname`, and `dirname`. - `basename` returns the last portion of the path passed in. - `extname` returns the extension of the last portion. Generally for directories, `extname` just returns ''. - Finally, `dirname` returns everything that `basename` does not return. + For example: - > var path = require('path') - > var a = '/a/b/c.html' - > path.basename(a) - 'c.html' - > path.extname(a) - '.html' - > path.dirname(a) - '/a/b' +``` +> var path = require('path') +> var a = '/a/b/c.html' +> path.basename(a) +'c.html' +> path.extname(a) +'.html' +> path.dirname(a) +'/a/b' +``` Note that `basename` has an optional second parameter that will strip out the extension if you pass the correct extension. - > var path = require('path') - > var a = '/a/b/c.html' - > path.basename(a, path.extname(a)) - 'c' +``` +> var path = require('path') +> var a = '/a/b/c.html' +> path.basename(a, path.extname(a)) +'c' +``` Lastly, the `path` module provides methods to check whether or not a given path exists: `exists` and `existsSync` They both take the path of a file for the first parameter. @@ -59,9 +70,11 @@ Lastly, the `path` module provides methods to check whether or not a given path Blocking isn't always a bad thing. Checking the existence of a vital configuration file synchronously makes sense, for example - it doesn't matter much if your process is blocking for something it can't run without! Conversely, though, in a busy HTTP server, any per-request file I/O **MUST** be asynchronous, or else you'll be responding to requests one by one. See the article on [asynchronous operations](/en/knowledge/getting-started/control-flow/how-to-write-asynchronous-code/) for more details. - > var path = require('path') - > path.exists('/etc', function(exists){console.log("Does the file exist?", exists)}) - > Does the file exist? true +``` +> var path = require('path') +> path.exists('/etc', function(exists){console.log("Does the file exist?", exists)}) +> Does the file exist? true - > path.existsSync('/etc') - true +> path.existsSync('/etc') +true +``` diff --git a/locale/en/knowledge/file-system/how-to-write-files-in-nodejs.md b/locale/en/knowledge/file-system/how-to-write-files-in-nodejs.md index b45699d4d7883..5433a3ce9cdec 100644 --- a/locale/en/knowledge/file-system/how-to-write-files-in-nodejs.md +++ b/locale/en/knowledge/file-system/how-to-write-files-in-nodejs.md @@ -9,8 +9,10 @@ layout: knowledge-post.hbs Writing to a file is another of the basic programming tasks that one usually needs to know about - luckily, this task is very simple in Node.js. We can use the handy `writeFile` method inside the standard library's `fs` module, which can save all sorts of time and trouble. - fs = require('fs'); - fs.writeFile(filename, data, [encoding], [callback]) +```javascript +fs = require('fs'); +fs.writeFile(filename, data, [encoding], [callback]) +``` `file = (string)` filepath of the file to read @@ -22,29 +24,37 @@ Writing to a file is another of the basic programming tasks that one usually nee So if we wanted to write "Hello World" to `helloworld.txt`: - fs = require('fs'); - fs.writeFile('helloworld.txt', 'Hello World!', function (err) { - if (err) return console.log(err); - console.log('Hello World > helloworld.txt'); - }); +```javascript +fs = require('fs'); +fs.writeFile('helloworld.txt', 'Hello World!', function (err) { + if (err) return console.log(err); + console.log('Hello World > helloworld.txt'); +}); +``` - [contents of helloworld.txt]: - Hello World! +``` +[contents of helloworld.txt]: +Hello World! +``` If we purposely want to cause an error, we can try to write to a file that we don't have permission to access: - fs = require('fs') - fs.writeFile('/etc/doesntexist', 'abc', function (err,data) { - if (err) { - return console.log(err); - } - console.log(data); - }); - - { stack: [Getter/Setter], - arguments: undefined, - type: undefined, - message: 'EACCES, Permission denied \'/etc/doesntexist\'', - errno: 13, - code: 'EACCES', - path: '/etc/doesntexist' } +```javascript +fs = require('fs') +fs.writeFile('/etc/doesntexist', 'abc', function (err,data) { + if (err) { + return console.log(err); + } + console.log(data); +}); +``` + +``` +{ stack: [Getter/Setter], + arguments: undefined, + type: undefined, + message: 'EACCES, Permission denied \'/etc/doesntexist\'', + errno: 13, + code: 'EACCES', + path: '/etc/doesntexist' } +``` diff --git a/locale/en/knowledge/file-system/security/introduction.md b/locale/en/knowledge/file-system/security/introduction.md index f5a01991d6b63..ff34a28c6965c 100644 --- a/locale/en/knowledge/file-system/security/introduction.md +++ b/locale/en/knowledge/file-system/security/introduction.md @@ -14,17 +14,21 @@ Sometimes, you might want to let users read or write files on your server. For e Poison null bytes are a way to trick your code into seeing another filename than the one that will actually be opened. This can in many cases be used to circumvent directory traversal protections, to trick servers into delivering files with wrong file types and to circumvent restrictions on the file names that may be used. [A more detailed description is here.](http://groups.google.com/group/nodejs/browse_thread/thread/51f66075e249d767/85f647474b564fde) Always use code like this when accessing files with user-supplied names: - if (filename.indexOf('\0') !== -1) { - return respond('That was evil.'); - } +```javascript +if (filename.indexOf('\0') !== -1) { + return respond('That was evil.'); +} +``` ## Whitelisting You won't always be able to use whitelisting, but if you are, do it - it's very easy to implement and hard to get wrong. For example, if you know that all filenames are lowercase alphanumeric strings: - if (!/^[a-z0-9]+$/.test(filename)) { - return respond('illegal character'); - } +```javascript +if (!/^[a-z0-9]+$/.test(filename)) { + return respond('illegal character'); +} +``` However, note that whitelisting alone isn't sufficient anymore as soon as you allow dots and slashes - people could enter things like `../../etc/passwd` in order to get files from outside the allowed folder. @@ -34,17 +38,23 @@ Directory traversal means that an attacker tries to access files outside of the This example assumes that you already checked the `userSuppliedFilename` variable as described in the "Poison Null Bytes" section above. - var rootDirectory = '/var/www/'; +```javascript +var rootDirectory = '/var/www/'; +``` Make sure that you have a slash at the end of the allowed folders name - you don't want people to be able to access `/var/www-secret/`, do you?. - var path = require('path'); - var filename = path.join(rootDirectory, userSuppliedFilename); +```javascript +var path = require('path'); +var filename = path.join(rootDirectory, userSuppliedFilename); +``` Now `filename` contains an absolute path and doesn't contain `..` sequences anymore - `path.join` takes care of that. However, it might be something like `/etc/passwd` now, so you have to check whether it starts with the `rootDirectory`: - if (filename.indexOf(rootDirectory) !== 0) { - return respond('trying to sneak out of the web root?'); - } +```javascript +if (filename.indexOf(rootDirectory) !== 0) { + return respond('trying to sneak out of the web root?'); +} +``` Now the `filename` variable should contain the name of a file or directory that's inside the allowed directory (unless it doesn't exist). diff --git a/locale/en/knowledge/getting-started/control-flow/how-to-write-asynchronous-code.md b/locale/en/knowledge/getting-started/control-flow/how-to-write-asynchronous-code.md index a224f8aaa80a2..890f8a5755260 100644 --- a/locale/en/knowledge/getting-started/control-flow/how-to-write-asynchronous-code.md +++ b/locale/en/knowledge/getting-started/control-flow/how-to-write-asynchronous-code.md @@ -17,19 +17,21 @@ Many of the functions in Node.js core have both synchronous and asynchronous ver As a quick example comparing and contrasting the two, using `fs.readFile`: - var fs = require('fs'); +```javascript +var fs = require('fs'); - fs.readFile('example.file', 'utf8', function (err, data) { - if (err) { - return console.log(err); - } - console.log(data); - }); +fs.readFile('example.file', 'utf8', function (err, data) { + if (err) { + return console.log(err); + } + console.log(data); +}); - //==================== +//==================== - var data = fs.readFileSync('example.file','utf8'); - console.log(data); +var data = fs.readFileSync('example.file','utf8'); +console.log(data); +``` Just looking at these two blocks of code, the synchronous version appears to be more concise. However, the asynchronous version is more complicated for a very good reason. In the synchronous version, the world is paused until the file is finished reading - your process will just sit there, waiting for the OS (which handles all file system tasks). @@ -46,34 +48,42 @@ Event Emitters are another basic idiom in node.js. A constructor is provided in ### A gotcha with asynchronous code A common mistake in asynchronous code with javascript is to write code that does something like this: - for (var i = 0; i < 5; i++) { - setTimeout(function () { - console.log(i); - }, i); - } +```javascript +for (var i = 0; i < 5; i++) { + setTimeout(function () { + console.log(i); + }, i); +} +``` The unexpected output is then: - 5 - 5 - 5 - 5 - 5 +``` +5 +5 +5 +5 +5 +``` The reason this happens is because each timeout is created and then `i` is incremented. Then when the callback is called, it looks for the value of `i` and it is 5. The solution is to create a closure so that the current value of `i` is stored. For example: - for (var i = 0; i < 5; i++) { - (function(i) { - setTimeout(function () { - console.log(i); - }, i); - })(i); - } +```javascript +for (var i = 0; i < 5; i++) { + (function(i) { + setTimeout(function () { + console.log(i); + }, i); + })(i); +} +``` This gives the proper output: - 0 - 1 - 2 - 3 - 4 +``` +0 +1 +2 +3 +4 +``` diff --git a/locale/en/knowledge/getting-started/control-flow/what-are-callbacks.md b/locale/en/knowledge/getting-started/control-flow/what-are-callbacks.md index b0d341662b1ee..17dbc4d4192b5 100644 --- a/locale/en/knowledge/getting-started/control-flow/what-are-callbacks.md +++ b/locale/en/knowledge/getting-started/control-flow/what-are-callbacks.md @@ -12,42 +12,48 @@ layout: knowledge-post.hbs In a synchronous program, you would write something along the lines of: - function processData () { - var data = fetchData (); - data += 1; - return data; - } +```javascript +function processData () { + var data = fetchData (); + data += 1; + return data; +} +``` This works just fine and is very typical in other development environments. However, if fetchData takes a long time to load the data (maybe it is streaming it off the drive or the internet), then this causes the whole program to 'block' - otherwise known as sitting still and waiting - until it loads the data. Node.js, being an asynchronous platform, doesn't wait around for things like file I/O to finish - Node.js uses callbacks. A callback is a function called at the completion of a given task; this prevents any blocking, and allows other code to be run in the meantime. The node.js way to deal with the above would look a bit more like this: - function processData (callback) { - fetchData(function (err, data) { - if (err) { - console.log("An error has occurred. Abort everything!"); - return callback(err); - } - data += 1; - callback(data); - }); +```javascript +function processData (callback) { + fetchData(function (err, data) { + if (err) { + console.log("An error has occurred. Abort everything!"); + return callback(err); } + data += 1; + callback(data); + }); +} +``` At first glance, it may look unnecessarily complicated, but callbacks are the foundation of Node.js. Callbacks give you an interface with which to say, "and when you're done doing that, do all this." This allows you to have as many IO operations as your OS can handle happening at the same time. For example, in a web server with hundreds or thousands of pending requests with multiple blocking queries, performing the blocking queries asynchronously gives you the ability to be able to continue working and not just sit still and wait until the blocking operations come back. This is a major improvement. The typical convention with asynchronous functions (which almost all of your functions should be): - function asyncOperation ( a, b, c, callback ) { - // ... lots of hard work ... - if ( /* an error occurs */ ) { - return callback(new Error("An error has occurred")); - } - // ... more work ... - callback(null, d, e, f); - } - - asyncOperation ( params.., function ( err, returnValues.. ) { - //This code gets run after the async operation gets run - }); +```javascript +function asyncOperation ( a, b, c, callback ) { + // ... lots of hard work ... + if ( /* an error occurs */ ) { + return callback(new Error("An error has occurred")); + } + // ... more work ... + callback(null, d, e, f); +} + +asyncOperation ( params.., function ( err, returnValues.. ) { + //This code gets run after the async operation gets run +}); +``` You will almost always want to follow the [error callback convention](/en/knowledge/errors/what-are-the-error-conventions/), since most Node.js users will expect your project to follow them. The general idea is that the callback is the last parameter. The callback gets called after the function is done with all of its operations. Traditionally, the first parameter of the callback is the `error` value. If the function hits an error, then they typically call the callback with the first parameter being an Error object. If it cleanly exits, then they will call the callback with the first parameter being null and the rest being the return value(s). diff --git a/locale/en/knowledge/getting-started/control-flow/what-are-event-emitters.md b/locale/en/knowledge/getting-started/control-flow/what-are-event-emitters.md index 49a7d4547e260..bdc1e74c56c3d 100644 --- a/locale/en/knowledge/getting-started/control-flow/what-are-event-emitters.md +++ b/locale/en/knowledge/getting-started/control-flow/what-are-event-emitters.md @@ -11,27 +11,31 @@ layout: knowledge-post.hbs In node.js an event can be described simply as a string with a corresponding callback. An event can be "emitted" (or in other words, the corresponding callback be called) multiple times or you can choose to only listen for the first time it is emitted. So a simple example ran on the node [REPL](/en/knowledge/REPL/how-to-use-nodejs-repl/): - var example_emitter = new (require('events').EventEmitter); - example_emitter.on("test", function () { console.log("test"); }); - example_emitter.on("print", function (message) { console.log(message); }); - example_emitter.emit("test"); - example_emitter.emit("print", "message"); - example_emitter.emit("unhandled"); - - > var example_emitter = new (require('events').EventEmitter); - {} - > example_emitter.on("test", function () { console.log("test"); }); - { _events: { test: [Function] } } - > example_emitter.on("print", function (message) { console.log(message); }); - { _events: { test: [Function], print: [Function] } } - > example_emitter.emit("test"); - test //console.log'd - true //return value - > example_emitter.emit("print", "message"); - message //console.log'd - true //return value - > example_emitter.emit("unhandled"); - false //return value +```javascript +var example_emitter = new (require('events').EventEmitter); +example_emitter.on("test", function () { console.log("test"); }); +example_emitter.on("print", function (message) { console.log(message); }); +example_emitter.emit("test"); +example_emitter.emit("print", "message"); +example_emitter.emit("unhandled"); +``` + +``` +> var example_emitter = new (require('events').EventEmitter); +{} +> example_emitter.on("test", function () { console.log("test"); }); +{ _events: { test: [Function] } } +> example_emitter.on("print", function (message) { console.log(message); }); +{ _events: { test: [Function], print: [Function] } } +> example_emitter.emit("test"); +test //console.log'd +true //return value +> example_emitter.emit("print", "message"); +message //console.log'd +true //return value +> example_emitter.emit("unhandled"); +false //return value +``` This demonstrates all the basic functionality of an EventEmitter. The `on` or `addListener` method (basically the subscription method) allows you to choose the event to watch for and the callback to be called. The `emit` method (the publish method), on the other hand, allows you to "emit" an event, which causes all callbacks registered to the event to 'fire', (get called). @@ -43,59 +47,63 @@ If you use the method `once` instead of `on`, after the callback is fired, it is If you want remove a specific callback, you can use `removeListener`. If you want to remove all callbacks to a specific event, you can use `removeAllListeners`. - var EventEmitter = require('events').EventEmitter, - ee = new EventEmitter(); - - function callback() { - console.log("Callback has been called!"); - } - - ee.once("event", callback); - ee.emit("event"); - ee.emit("event"); - - ee.on("event", callback); - ee.emit("event"); - ee.emit("event"); - ee.removeListener("event", callback); - ee.emit("event"); - - ee.on("event", callback); - ee.emit("event"); - ee.removeAllListeners("event"); - ee.emit("event"); - - > var ee = new (require('events').EventEmitter); - > var callback = function () { console.log("Callbacked!"); } - > ee.once("event", callback); - { _events: { event: { [Function: g] listener: [Function] } } } - > ee.emit("event"); - Callbacked! //console.log'd - true - > ee.emit("event"); - false - - > ee.on("event", callback); - { _events: { event: [Function] } } - > ee.emit("event"); - Callbacked! //console.log'd - true - > ee.emit("event"); - Callbacked! //console.log'd - true - > ee.removeListener("event", callback); - { _events: {} } - > ee.emit("event"); - false - - > ee.on("event", callback); - { _events: { event: [Function] } } - > ee.emit("event"); - Callbacked! //console.log'd - true - > ee.removeAllListeners("event"); - { _events: { event: null } } - > ee.emit("event"); - false +```javascript +var EventEmitter = require('events').EventEmitter, + ee = new EventEmitter(); + +function callback() { + console.log("Callback has been called!"); +} + +ee.once("event", callback); +ee.emit("event"); +ee.emit("event"); + +ee.on("event", callback); +ee.emit("event"); +ee.emit("event"); +ee.removeListener("event", callback); +ee.emit("event"); + +ee.on("event", callback); +ee.emit("event"); +ee.removeAllListeners("event"); +ee.emit("event"); +``` + +``` +> var ee = new (require('events').EventEmitter); +> var callback = function () { console.log("Callbacked!"); } +> ee.once("event", callback); +{ _events: { event: { [Function: g] listener: [Function] } } } +> ee.emit("event"); +Callbacked! //console.log'd +true +> ee.emit("event"); +false + +> ee.on("event", callback); +{ _events: { event: [Function] } } +> ee.emit("event"); +Callbacked! //console.log'd +true +> ee.emit("event"); +Callbacked! //console.log'd +true +> ee.removeListener("event", callback); +{ _events: {} } +> ee.emit("event"); +false + +> ee.on("event", callback); +{ _events: { event: [Function] } } +> ee.emit("event"); +Callbacked! //console.log'd +true +> ee.removeAllListeners("event"); +{ _events: { event: null } } +> ee.emit("event"); +false +``` NOTE: If you want create more than 10 listeners on a single event, you will have to make a call to `ee.setMaxListeners(n)` where n is the max numbers of listeners (with zero being unlimited number of listeners). This is used to make sure you aren't accidentally leaking event listeners. diff --git a/locale/en/knowledge/getting-started/how-to-debug-nodejs-applications.md b/locale/en/knowledge/getting-started/how-to-debug-nodejs-applications.md index 69e0ab0145409..50457b6904863 100644 --- a/locale/en/knowledge/getting-started/how-to-debug-nodejs-applications.md +++ b/locale/en/knowledge/getting-started/how-to-debug-nodejs-applications.md @@ -15,29 +15,37 @@ Thankfully, through the use of `node-inspector`, we can harness to power of the First, ensure that node-inspector is installed: - npm install node-inspector -g +``` +npm install node-inspector -g +``` A good example application to experiment with is a basically 'hello world' server with a counter (copied from the `node-inspector` repo): - var http = require('http'); +```javascript +var http = require('http'); - var x = 0; - http.createServer(function (req, res) { - x += 1; - res.writeHead(200, {'Content-Type': 'text/plain'}); - res.end('Hello World ' + x); - }).listen(8124); - console.log('Server running at http://127.0.0.1:8124/'); +var x = 0; +http.createServer(function (req, res) { + x += 1; + res.writeHead(200, {'Content-Type': 'text/plain'}); + res.end('Hello World ' + x); +}).listen(8124); +console.log('Server running at http://127.0.0.1:8124/'); +``` First, we start your node program with debugging enabled. - node --debug app.js +``` +node --debug app.js +``` which should print something along the lines of `debugger listening on port 5858` to stderr. Take note of the port number, it is the port that the debugger is running on. Next, start up `node-inspector`. If your program uses port 8080, then you may have to pass it a custom port. - node-inspector [--web-port=] +``` +node-inspector [--web-port=] +``` Finally you fire up a webkit browser such as chrome or safari. and go to `127.0.0.1:8080/debug?port=5858`. Note, if the debugger is listening on a port other than `5858`, you will need to change it. Also, if you passed a custom webport to node-inspector, then you will have to modify the `8080`. @@ -51,39 +59,49 @@ This is just like most webkit/firebug debuggers. It has a list of all the javasc To use the profile tab, you need a library called `v8-profiler`: - npm install v8-profiler +``` +npm install v8-profiler +``` Next, you have to require it inside the file you are debugging: - var profiler = require('v8-profiler'); +```javascript +var profiler = require('v8-profiler'); +``` Now you can finally enable the `profiles` tab, unfortunately, all you can do from this screen is a heap snapshot. So from the code, you need to select where you want to start to cpu profiler and can select more precise location for heap snapshots. To take a heap snapshot, just insert this line in the desired location and optionally pass it a name. - var snapshot = profiler.takeSnapshot(name); +```javascript +var snapshot = profiler.takeSnapshot(name); +``` To take a cpu profile, just surround the code that you are profiling with the two lines shown below. Optionally, a name can be included to indentify the cpu profile. - profiler.startProfiling(name); - //..lots and lots of methods and code called..// - var cpuProfile = profiler.stopProfiling([name]); +```javascript +profiler.startProfiling(name); +//..lots and lots of methods and code called..// +var cpuProfile = profiler.stopProfiling([name]); +``` As an example how to use these, here is the code given earlier modified to take a cpu profile on every request and take a heap snapshot: after the server is created. - var http = require('http'); - var profiler = require('v8-profiler'); - - var x = 0; - http.createServer(function (req, res) { - x += 1; - profiler.startProfiling('request '+x); - res.writeHead(200, {'Content-Type': 'text/plain'}); - res.end('Hello World ' + x); - profiler.stopProfiling('request '+x); - }).listen(8124); - profiler.takeSnapshot('Post-Server Snapshot'); - console.log('Server running at http://127.0.0.1:8124/'); +```javascript +var http = require('http'); +var profiler = require('v8-profiler'); + +var x = 0; +http.createServer(function (req, res) { + x += 1; + profiler.startProfiling('request '+x); + res.writeHead(200, {'Content-Type': 'text/plain'}); + res.end('Hello World ' + x); + profiler.stopProfiling('request '+x); +}).listen(8124); +profiler.takeSnapshot('Post-Server Snapshot'); +console.log('Server running at http://127.0.0.1:8124/'); +``` Note that despite these apis returning objects, it is much easier to sort through the data through the node-inspector interface. Hopefully with these tools, you can make more informed decisions about memory leaks and bottlenecks. diff --git a/locale/en/knowledge/getting-started/how-to-use-util-inspect.md b/locale/en/knowledge/getting-started/how-to-use-util-inspect.md index 3be524f13edfe..5907bc92b8539 100644 --- a/locale/en/knowledge/getting-started/how-to-use-util-inspect.md +++ b/locale/en/knowledge/getting-started/how-to-use-util-inspect.md @@ -12,37 +12,51 @@ Node provides a utility function, for debugging purposes, that returns a string Let's provide a basic example. `util.inspect()` can be used on any object - a good demonstration will be one of Node's built-in objects. Try this in the REPL (type `node` at your command line with no arguments): - var util = require('util'); - util.inspect(console); +```javascript +var util = require('util'); +util.inspect(console); +``` The output will be: - '{ log: [Function], info: [Function], warn: [Function], error: [Function], dir: [Function], time: [Function], timeEnd: [Function], trace: [Function], assert: [Function] }' +``` +'{ log: [Function], info: [Function], warn: [Function], error: [Function], dir: [Function], time: [Function], timeEnd: [Function], trace: [Function], assert: [Function] }' +``` This is a listing of all the enumerable properties of the `console` object. It is also worth noting that `console.dir` is a wrapper around `util.inspect` that uses its default arguments. In the REPL, `util.inspect` will immediately return its output - this is not usually the case. In the context of normal Node.js code in a file, something must be done with the output. The simplest thing to do: - console.log(util.inspect(myObj)); +```javascript +console.log(util.inspect(myObj)); +``` `util.inspect` can also be passed several optional arguments, shown here with their defaults: - util.inspect(object, showHidden=false, depth=2, colorize=true); +```javascript +util.inspect(object, showHidden=false, depth=2, colorize=true); +``` For example, `util.inspect(myObj, true, 7, true)` would inspect `myObj`, showing all the hidden and non-hidden properties up to a depth of `7` and colorize the output. Let's go over the arguments individually. The `depth` argument is the number of levels deep into a nested object to recurse - it defaults to 2. Setting it to `null` will cause it to recurse 'all the way', showing every level. Compare the (size of) the outputs of these two `util.inspect` statements in the REPL: - var http = require('http'); - util.inspect(http, true, 1); - util.inspect(http, true, 3); +```javascript +var http = require('http'); +util.inspect(http, true, 1); +util.inspect(http, true, 3); +``` The optional argument `showHidden` is a boolean that determines whether or not the 'non-enumerable' properties of an object will be displayed - it defaults to `false`, which tends to result in vastly more readable output. This isn't something a beginner needs to worry about most of the time, but it's worth demonstrating briefly. Once more, try the following in the REPL: - var util = require('util'); - util.inspect(console, true); +```javascript +var util = require('util'); +util.inspect(console, true); +``` Finally, the optional argument `colorize` is a boolean that adds ANSI escape codes to the string output. When logged to a terminal window, it should be pretty printed with colors. - var util = require('util'); - console.log(util.inspect({a:1, b:"b"}, false,2,true)); +```javascript +var util = require('util'); +console.log(util.inspect({a:1, b:"b"}, false,2,true)); +``` diff --git a/locale/en/knowledge/getting-started/npm/how-to-access-module-package-info.md b/locale/en/knowledge/getting-started/npm/how-to-access-module-package-info.md index 1f7457256ae52..738c7ed6a005c 100644 --- a/locale/en/knowledge/getting-started/npm/how-to-access-module-package-info.md +++ b/locale/en/knowledge/getting-started/npm/how-to-access-module-package-info.md @@ -12,19 +12,25 @@ There are many situations in the world of software development where using the w Let's take a look at pkginfo - first, install via npm: - npm install pkginfo +``` +npm install pkginfo +``` Now all we need to do is require it, and invoke it. - var pkginfo = require('pkginfo')(module); +```javascript +var pkginfo = require('pkginfo')(module); - console.dir(module.exports); +console.dir(module.exports); +``` That would show us the entire contents of the package.json, neatly displayed to our console. If we only wanted certain pieces of information, we just specify them like so: - var pkginfo = require('pkginfo')(module, 'version', 'author'); +```javascript +var pkginfo = require('pkginfo')(module, 'version', 'author'); - console.dir(module.exports); +console.dir(module.exports); +``` And only the fields we specify will be shown to us. diff --git a/locale/en/knowledge/getting-started/npm/what-is-npm.md b/locale/en/knowledge/getting-started/npm/what-is-npm.md index 7cf08bb7191e2..c36eaca253bdd 100644 --- a/locale/en/knowledge/getting-started/npm/what-is-npm.md +++ b/locale/en/knowledge/getting-started/npm/what-is-npm.md @@ -17,8 +17,10 @@ Another important use for npm is dependency management. When you have a node pr Example: - git clone https://github.com/cloudhead/vows.git - cd vows - npm install +``` +git clone https://github.com/cloudhead/vows.git +cd vows +npm install +``` After running those commands, you will see a `node_modules` folder containing all of the project dependencies specified in the package.json. diff --git a/locale/en/knowledge/getting-started/npm/what-is-the-file-package-json.md b/locale/en/knowledge/getting-started/npm/what-is-the-file-package-json.md index 7991b412a247b..a25da6c8168f9 100644 --- a/locale/en/knowledge/getting-started/npm/what-is-the-file-package-json.md +++ b/locale/en/knowledge/getting-started/npm/what-is-the-file-package-json.md @@ -13,27 +13,31 @@ All npm packages contain a file, usually in the project root, called `package.js Node itself is only aware of two fields in the `package.json`: - { - "name" : "barebones", - "version" : "0.0.0", - } +```json +{ + "name" : "barebones", + "version" : "0.0.0", +} +``` The `name` field should explain itself: this is the name of your project. The `version` field is used by npm to make sure the right version of the package is being installed. Generally, it takes the form of `major.minor.patch` where `major`, `minor`, and `patch` are integers which increase after each new release. For more details, look at this spec: http://semver.org . For a more complete package.json, we can check out `underscore`: - { - "name" : "underscore", - "description" : "JavaScript's functional programming helper library.", - "homepage" : "http://documentcloud.github.com/underscore/", - "keywords" : ["util", "functional", "server", "client", "browser"], - "author" : "Jeremy Ashkenas ", - "contributors" : [], - "dependencies" : [], - "repository" : {"type": "git", "url": "git://github.com/documentcloud/underscore.git"}, - "main" : "underscore.js", - "version" : "1.1.6" - } +```json +{ + "name" : "underscore", + "description" : "JavaScript's functional programming helper library.", + "homepage" : "http://documentcloud.github.com/underscore/", + "keywords" : ["util", "functional", "server", "client", "browser"], + "author" : "Jeremy Ashkenas ", + "contributors" : [], + "dependencies" : [], + "repository" : {"type": "git", "url": "git://github.com/documentcloud/underscore.git"}, + "main" : "underscore.js", + "version" : "1.1.6" +} +``` As you can see, there are fields for the `description` and `keywords` of your projects. This allows people who find your project understand what it is in just a few words. The `author`, `contributors`, `homepage` and `repository` fields can all be used to credit the people who contributed to the project, show how to contact the author/maintainer, and give links for additional references. diff --git a/locale/en/knowledge/getting-started/the-console-module.md b/locale/en/knowledge/getting-started/the-console-module.md index 49cb8c598274d..65786e1071f58 100644 --- a/locale/en/knowledge/getting-started/the-console-module.md +++ b/locale/en/knowledge/getting-started/the-console-module.md @@ -13,22 +13,26 @@ Anyone familiar with browser-side development has probably used `console.log` fo Because of this browser parallel, the `console` module has become home to quite a bit of Node's standard output functionality. The simplest is `console.log()`. - console.log('Hi, everybody!'); - console.log('This script is:', __filename); - console.log(__filename, process.title, process.argv); +```javascript +console.log('Hi, everybody!'); +console.log('This script is:', __filename); +console.log(__filename, process.title, process.argv); +``` The first, simplest example just prints the provided string to `stdout`. It can also be used to output the contents of variables, as evidenced in #2; furthermore, `console.dir()` is called on any objects passed in as arguments, enumerating their properties. NODE.JS PRO TIP: `console.log()` accepts three format characters, `%s`, `%d`, and `%j`. These format characters can be used to insert string, integer, or JSON data into your output - the order of format characters must match the order of arguments. - var name = 'Harry', - number = 17, - myObj = { - propOne: 'stuff', - propTwo: 'more stuff' - }; - console.log('My name is %s, my number is %d, my object is %j', name, number, myObj); +```javascript +var name = 'Harry', + number = 17, + myObj = { + propOne: 'stuff', + propTwo: 'more stuff' + }; +console.log('My name is %s, my number is %d, my object is %j', name, number, myObj); +``` A gotcha with `console.log`, and all functions that depend on it, is that it buffers the output. So if your process ends suddenly, whether it be from an exception or from `process.exit()`, it is entirely possible that the buffered output will never reach the screen. This can cause a great deal of frustration, so watch out for this unfortunate situation. @@ -38,14 +42,16 @@ A gotcha with `console.log`, and all functions that depend on it, is that it buf That covers the basic `console` module functionality, but there are a few other methods worth mentioning as well. First, the `console` module allows for the marking of time via `console.time()` and `console.timeEnd()`. Here is an example: - console.time('myTimer'); - var string = ''; - for (var i = 0; i < 300; i++) { - (function (i) { - string += 'aaaa' + i.toString(); - })(i); - } - console.timeEnd('myTimer'); +```javascript +console.time('myTimer'); +var string = ''; +for (var i = 0; i < 300; i++) { + (function (i) { + string += 'aaaa' + i.toString(); + })(i); +} +console.timeEnd('myTimer'); +``` This would determine the amount of time taken to perform the actions in between the `console.time` and `console.timeEnd` calls. diff --git a/locale/en/knowledge/getting-started/the-process-module.md b/locale/en/knowledge/getting-started/the-process-module.md index 397e35ea1aa87..c49a52e80cfc0 100644 --- a/locale/en/knowledge/getting-started/the-process-module.md +++ b/locale/en/knowledge/getting-started/the-process-module.md @@ -16,18 +16,22 @@ There are two built-in events worth noting in the `process` module, `exit` and ` The `exit` event fires whenever the process is about to exit. - process.on('exit', function () { - fs.writeFileSync('/tmp/myfile', 'This MUST be saved on exit.'); - }); +```javascript +process.on('exit', function () { + fs.writeFileSync('/tmp/myfile', 'This MUST be saved on exit.'); +}); +``` Code like the above can occasionally be useful for saving some kind of final report before you exit. Note the use of a synchronous file system call - this is to make sure the I/O finishes before the process actually exits. The other built-in event is called `uncaughtException`. It fires, as you might guess, whenever an exception has occurred that hasn't been caught or dealt with somewhere else in your program. It's not the ideal way to handle errors, but it can be very useful as a last line of defense if a program needs to stay running indefinitely. - process.on('uncaughtException', function (err) { - console.error('An uncaught error occurred!'); - console.error(err.stack); - }); +```javascript +process.on('uncaughtException', function (err) { + console.error('An uncaught error occurred!'); + console.error(err.stack); +}); +``` The default behavior on `uncaughtException` is to print a stack trace and exit - using the above, your program will display the message provided and the stack trace, but will **not** exit. @@ -37,9 +41,11 @@ The `process` object also provides wrappings for the three `STDIO` streams, `std The simplest one to describe is `process.stdout`. Technically, most output in Node is accomplished by using `process.stdout.write()` - though most people would never know it. The following is from `console.js` in Node core: - exports.log = function() { - process.stdout.write(format.apply(this, arguments) + '\n'); - }; +```javascript +exports.log = function() { + process.stdout.write(format.apply(this, arguments) + '\n'); +}; +``` Since most people are used to the `console.log` syntax from browser development, it was provided as a convenient wrapper. @@ -55,14 +61,16 @@ Lastly, `process.stdin` is a readable stream for getting user input. See [more The `process` object additionally contains a variety of properties that allow you to access information about the running process. Let's run through a few quick examples with the help of the REPL: - > process.pid - 3290 - > process.version - 'v0.4.9' - > process.platform - 'linux' - > process.title - 'node' +``` +> process.pid +3290 +> process.version +'v0.4.9' +> process.platform +'linux' +> process.title +'node' +``` The `pid` is the OS Process ID, `platform` is something general like 'linux' or 'darwin', and `version` refers to your Node version. `process.title` is a little bit different - while set to `node` by default, it can be set to anything you want, and will be what gets displayed in lists of running processes. @@ -82,22 +90,28 @@ There are also a variety of methods attached to the `process` object, many of wh `process.chdir` is used to change the current working directory. For example: - > process.cwd() - '/home/avian/dev' - > process.chdir('/home/avian') - > process.cwd() - '/home/avian' +``` +> process.cwd() +'/home/avian/dev' +> process.chdir('/home/avian') +> process.cwd() +'/home/avian' +``` Finally, on a more advanced note, we have `process.nextTick`. This method accepts one argument - a callback - and places it at the top of the next iteration of the event loop. Some people do something like this: - setTimeout(function () { - // code here - }, 0) +```javascript +setTimeout(function () { + // code here +}, 0) +``` This, however, is not ideal. In Node.js, this should be used instead: - process.nextTick(function () { - console.log('Next trip around the event loop, wheeee!') - }); +```javascript +process.nextTick(function () { + console.log('Next trip around the event loop, wheeee!') +}); +``` It is much more efficient, and much more accurate. diff --git a/locale/en/knowledge/getting-started/what-is-require.md b/locale/en/knowledge/getting-started/what-is-require.md index f79b5a472f175..7bf4797d98f5d 100644 --- a/locale/en/knowledge/getting-started/what-is-require.md +++ b/locale/en/knowledge/getting-started/what-is-require.md @@ -12,44 +12,52 @@ layout: knowledge-post.hbs Node.js follows the CommonJS module system, and the builtin `require` function is the easiest way to include modules that exist in separate files. The basic functionality of `require` is that it reads a javascript file, executes the file, and then proceeds to return the `exports` object. An example module: - console.log("evaluating example.js"); +```javascript +console.log("evaluating example.js"); - var invisible = function () { - console.log("invisible"); - } +var invisible = function () { + console.log("invisible"); +} - exports.message = "hi"; +exports.message = "hi"; - exports.say = function () { - console.log(exports.message); - } +exports.say = function () { + console.log(exports.message); +} +``` So if you run `var example = require('./example.js')`, then `example.js` will get evaluated and then `example` be an object equal to: - { - message: "hi", - say: [Function] - } +``` +{ + message: "hi", + say: [Function] +} +``` If you want to set the exports object to a function or a new object, you have to use the `module.exports` object. So for an example: - module.exports = function () { - console.log("hello world") - } +```javascript +module.exports = function () { + console.log("hello world") +} - require('./example2.js')() //require itself and run the exports object +require('./example2.js')() //require itself and run the exports object +``` It is worth noting that each time you subsequently require an already-required file, the `exports` object is cached and reused. To illustrate this point: - node> require('./example.js') - evaluating example.js - { message: 'hi', say: [Function] } - node> require('./example.js') - { message: 'hi', say: [Function] } - node> require('./example.js').message = "hey" //set the message to "hey" - 'hey' - node> require('./example.js') //One might think that this "reloads" the file... - { message: 'hey', say: [Function] } //...but the message is still "hey" because of the module cache. +``` +node> require('./example.js') +evaluating example.js +{ message: 'hi', say: [Function] } +node> require('./example.js') +{ message: 'hi', say: [Function] } +node> require('./example.js').message = "hey" //set the message to "hey" +'hey' +node> require('./example.js') //One might think that this "reloads" the file... +{ message: 'hey', say: [Function] } //...but the message is still "hey" because of the module cache. +``` As you can see from the above, `example.js` is evaluated the first time, but all subsequent calls to `require()` only invoke the module cache, rather than reading the file again. As seen above, this can occasionally produce side effects. diff --git a/locale/en/knowledge/intermediate/how-to-log.md b/locale/en/knowledge/intermediate/how-to-log.md index 2da48d382b7ba..1e56ae7edfd6f 100644 --- a/locale/en/knowledge/intermediate/how-to-log.md +++ b/locale/en/knowledge/intermediate/how-to-log.md @@ -13,7 +13,9 @@ Many processes, including most servers, write logs in one form or another. Reaso The simplest form of logging involves simply using `console.log` or one of the other standard output methods. In this approach, any information is printed to `stdout` where it can either be read by the developer as it occurs, or, for example, redirected to a log file. - console.log('Web Server started, waiting for connections...'); +```javascript +console.log('Web Server started, waiting for connections...'); +``` Because it's so simple, console.log is by far the most common way of logging data in node.js. @@ -23,25 +25,29 @@ Logging only with functions such as `console.log` is not ideal for every use cas Here is an example of a basic custom logging module with configurable debugging levels. - var logger = exports; - logger.debugLevel = 'warn'; - logger.log = function(level, message) { - var levels = ['info', 'warn', 'error']; - if (levels.indexOf(level) <= levels.indexOf(logger.debugLevel) ) { - if (typeof message !== 'string') { - message = JSON.stringify(message); - }; - console.log(level+': '+message); - } - } +```javascript +var logger = exports; +logger.debugLevel = 'warn'; +logger.log = function(level, message) { + var levels = ['info', 'warn', 'error']; + if (levels.indexOf(level) <= levels.indexOf(logger.debugLevel) ) { + if (typeof message !== 'string') { + message = JSON.stringify(message); + }; + console.log(level+': '+message); + } +} +``` Usage would then look like the following: - var logger = require('./logger'); - logger.debugLevel = 'warn'; - logger.log('info', 'Everything started properly.'); - logger.log('warn', 'Running out of memory...'); - logger.log('error', { error: 'flagrant'}); +```javascript +var logger = require('./logger'); +logger.debugLevel = 'warn'; +logger.log('info', 'Everything started properly.'); +logger.log('warn', 'Running out of memory...'); +logger.log('error', { error: 'flagrant'}); +``` Because `logger.debugLevel` was set to `warn`, the warning message and the error would both be displayed, but the `info` message would not be. @@ -53,37 +59,45 @@ The advantage here is that the behavior of our logging mechanisms can now be mod Here is an example of setting up a `winston` logger. This example includes most of the transports one could ever possibly want - please note that most use cases will only warrant a few of these. - var winston = require('winston'); - - require('winston-riak').Riak; - require('winston-mongo').Mongo; - require('winston-couchdb').Couchdb; - - var logger = new (winston.Logger)({ - transports: [ - new winston.transports.Console(), - new winston.transports.File({ filename: 'path/to/all-logs.log' }), - new winston.transports.Couchdb({ 'host': 'localhost', 'db': 'logs' }), - new winston.transports.Riak({ bucket: 'logs' }), - new winston.transports.MongoDB({ db: 'db', level: 'info'}) - ], - exceptionHandlers: [ - new winston.transports.File({ filename: 'path/to/exceptions.log' }) - ] - }); +```javascript +var winston = require('winston'); + +require('winston-riak').Riak; +require('winston-mongo').Mongo; +require('winston-couchdb').Couchdb; + +var logger = new (winston.Logger)({ + transports: [ + new winston.transports.Console(), + new winston.transports.File({ filename: 'path/to/all-logs.log' }), + new winston.transports.Couchdb({ 'host': 'localhost', 'db': 'logs' }), + new winston.transports.Riak({ bucket: 'logs' }), + new winston.transports.MongoDB({ db: 'db', level: 'info'}) + ], + exceptionHandlers: [ + new winston.transports.File({ filename: 'path/to/exceptions.log' }) + ] +}); +``` Here, we have instantiated a new `winston` logger, and provided a number of logging transports. Winston has built-in support for configurable logging levels, and provides alias methods for each configured logging level. For example, `winston.warn(x)` is an alias for `winston.log('warn', x)`. Thus, the following: - logger.warn('Hull Breach Detected on Deck 7!'); +```javascript +logger.warn('Hull Breach Detected on Deck 7!'); +``` Would output to the screen: - warn: Hull Breach Detected on Deck 7! +``` +warn: Hull Breach Detected on Deck 7! +``` Because of the file transport we set up, winston also logged the warning to 'somefile.log'. After the `logger.warn` call we just used, the log file, `somefile.log`, would contain the following output: - $ cat somefile.log - {'level':'warn','message':'Hull Breach Detected on Deck 7!'} +``` +$ cat somefile.log +{'level':'warn','message':'Hull Breach Detected on Deck 7!'} +``` Note that winston's file logger formats the logs differently for file logging (JSON in this case) than it does for the console transport. diff --git a/locale/pt-br/knowledge/advanced/streams/how-to-use-fs-create-write-stream.md b/locale/pt-br/knowledge/advanced/streams/how-to-use-fs-create-write-stream.md index 562a2d32ede7e..e690fe55a0379 100644 --- a/locale/pt-br/knowledge/advanced/streams/how-to-use-fs-create-write-stream.md +++ b/locale/pt-br/knowledge/advanced/streams/how-to-use-fs-create-write-stream.md @@ -11,24 +11,26 @@ layout: knowledge-post.hbs A função `fs.createWriteStream()` cria um fluxo corrente de uma maneira muito simples. Depois de chamar a função `fs.createWriteStream` com o caminho da pasta, você tem um fluxo corrente. Os objetos de respostas (assim como a solicitação) são fluxos. Então vamos transmitir os dados `POST` para o arquivo `output`. Como o código é simples, é muito fácil lê-lo e comentar por que cada linha é necessária. - var http = require('http'); - var fs = require('fs'); +```javascript +var http = require('http'); +var fs = require('fs'); - http.createServer(function(req, res) { - // Isso abre o fluxo corrente para `output` - var writeStream = fs.createWriteStream('./output'); +http.createServer(function(req, res) { + // Isso abre o fluxo corrente para `output` + var writeStream = fs.createWriteStream('./output'); - // O pipe leva os dados POST para o arquivo - req.pipe(writeStream); + // O pipe leva os dados POST para o arquivo + req.pipe(writeStream); - // Depois de todos os dados serem salvos, responde com um simples formulário html para que eles possam postar mais dados - req.on('end', function () { - res.writeHead(200, {"content-type":"text/html"}); - res.end('
'); - }); + // Depois de todos os dados serem salvos, responde com um simples formulário html para que eles possam postar mais dados + req.on('end', function () { + res.writeHead(200, {"content-type":"text/html"}); + res.end('
'); + }); - // Caso algum erro ocorra - writeStream.on('error', function (err) { - console.log(err); - }); - }).listen(8080); + // Caso algum erro ocorra + writeStream.on('error', function (err) { + console.log(err); + }); +}).listen(8080); +``` diff --git a/locale/pt-br/knowledge/errors/what-are-the-error-conventions.md b/locale/pt-br/knowledge/errors/what-are-the-error-conventions.md index 453268c25b308..328a9dde7c8bc 100644 --- a/locale/pt-br/knowledge/errors/what-are-the-error-conventions.md +++ b/locale/pt-br/knowledge/errors/what-are-the-error-conventions.md @@ -14,42 +14,38 @@ No node.js, considera-se uma prática padrão lidar com erros em funções assí É mais simples do que parece; vamos demonstrar. - var isTrue = function(value, callback) { - if (value === true) { - callback(null, "O valor era verdadeiro."); - } - else { - callback(new Error("O valor não era verdadeiro!; - } - } - - var callback = function (error, retval) { - if (error) { - console.log(error); - return; - } - console.log(retval); - } - - - // Note: quando chamamos a mesma função assíncrona duas vezes, você está em uma condição de corrida. - // Você não tem como saber com certeza qual retorno de chamada será chamado primeiro ao chamar as funções dessa maneira. - - isTrue(false, callback); - isTrue(true, callback); - - { stack: [Getter/Setter], - arguments: undefined, - type: undefined, - message: 'O valor não era verdadeiro!' } - O valor era verdadeiro. +```javascript +var isTrue = function(value, callback) { + if (value === true) { + callback(null, "O valor era verdadeiro."); + } + else { + callback(new Error("O valor não era verdadeiro!")); + } +} + +var callback = function (error, retval) { + if (error) { + console.log(error); + return; + } + console.log(retval); +} + +// Note: quando chamamos a mesma função assíncrona duas vezes, você está em uma condição de corrida. +// Você não tem como saber com certeza qual retorno de chamada será chamado primeiro ao chamar as funções dessa maneira. + +isTrue(false, callback); +isTrue(true, callback); +``` + +``` +{ stack: [Getter/Setter], + arguments: undefined, + type: undefined, + message: 'O valor não era verdadeiro!' } +O valor era verdadeiro. +``` Como você pode ver no exemplo, o callback é chamado recebendo null como o primeiro argumento se não houver erros. Todavia, se houver um erro, é criado um objeto `Error`, que então se torna o único parâmetro de retorno da chamada. diff --git a/locale/pt-br/knowledge/errors/what-is-the-error-object.md b/locale/pt-br/knowledge/errors/what-is-the-error-object.md index df7ce0a502a22..9947d54a0b266 100644 --- a/locale/pt-br/knowledge/errors/what-is-the-error-object.md +++ b/locale/pt-br/knowledge/errors/what-is-the-error-object.md @@ -13,24 +13,28 @@ O objeto Error é um objeto interno que fornece um conjunto padrão de informaç Código: - var error = new Error("A mensagem de erro"); - console.log(error); - console.log(error.stack); +```javascript +var error = new Error("A mensagem de erro"); +console.log(error); +console.log(error.stack); +``` Resultado: - { stack: [Getter/Setter], - arguments: undefined, - type: undefined, - message: 'A mensagem de erro' } - Error: A mensagem de erro - at Object. (/home/nico/example.js:1:75) - at Module._compile (module.js:407:26) - at Object..js (module.js:413:10) - at Module.load (module.js:339:31) - at Function._load (module.js:298:12) - at Array.0 (module.js:426:10) - at EventEmitter._tickCallback (node.js:126:26) +``` +{ stack: [Getter/Setter], + arguments: undefined, + type: undefined, + message: 'A mensagem de erro' } +Error: A mensagem de erro + at Object. (/home/nico/example.js:1:75) + at Module._compile (module.js:407:26) + at Object..js (module.js:413:10) + at Module.load (module.js:339:31) + at Function._load (module.js:298:12) + at Array.0 (module.js:426:10) + at EventEmitter._tickCallback (node.js:126:26) +``` `error.stack` exibe de onde o erro veio, assim como a lista das chamadas de funções que o procederam - por convenção, `error.stack` sempre imprime `error.message` como a primeira linha de saída, tornando o `error.stack` uma conveniente propriedade para imprimir durante a depuração. @@ -38,9 +42,11 @@ Resultado: Se você quiser/precisar adicionar mais informações ao objeto Error, você pode sempre adicionar propriedades, assim como em qualquer outro objeto em JavaScript: - var error = new Error("A mensagem de erro"); - error.http_code = 404; - console.log(error); +```javascript +var error = new Error("A mensagem de erro"); +error.http_code = 404; +console.log(error); +``` Para mais detalhes sobre como usar o objeto Error, confira o [artigo sobre convenções de erro](/pt-br/knowledge/errors/what-are-the-error-conventions/) diff --git a/locale/pt-br/knowledge/errors/what-is-try-catch.md b/locale/pt-br/knowledge/errors/what-is-try-catch.md index b4cc3ea143e01..e0a4bca927cfc 100644 --- a/locale/pt-br/knowledge/errors/what-is-try-catch.md +++ b/locale/pt-br/knowledge/errors/what-is-try-catch.md @@ -10,33 +10,37 @@ layout: knowledge-post.hbs Exemplo: - console.log("entrando na instrução try-catch"); - - try { - console.log("entrando no bloco try"); - throw "lançar mensagem"; - console.log("esta mensagem nunca será vista"); - } - catch (e) { - console.log("entrando no bloco catch"); - console.log(e); - console.log("saindo do bloco catch"); - } - finally { - console.log("entrando e saindo do bloco finally"); - } - - console.log("saindo da instrução try-catch"); +```javascript +console.log("entrando na instrução try-catch"); + +try { + console.log("entrando no bloco try"); + throw "lançar mensagem"; + console.log("esta mensagem nunca será vista"); +} +catch (e) { + console.log("entrando no bloco catch"); + console.log(e); + console.log("saindo do bloco catch"); +} +finally { + console.log("entrando e saindo do bloco finally"); +} + +console.log("saindo da instrução try-catch"); +``` Results: - entrando na instrução try-catch - entrando no bloco try - entrando no bloco catch - lançar mensagem - saindo do bloco catch - entrando e saindo do bloco finally - saindo da instrução try-catch +``` +entrando na instrução try-catch +entrando no bloco try +entrando no bloco catch +lançar mensagem +saindo do bloco catch +entrando e saindo do bloco finally +saindo da instrução try-catch +``` A instrução de `try-catch-finally` em JavaScript funciona de forma muito semelhante ao `try-catch-finally` encontrado em C++ e Java. Primeiro, o bloco try é executado até e a menos que o código nele dispare uma exceção (se houver uma instrução explícita `throw`, o código possui uma exceção nativa não identificado, ou se o código chamar uma função que usa `throw`). diff --git a/locale/pt-br/knowledge/file-system/how-to-read-files-in-nodejs.md b/locale/pt-br/knowledge/file-system/how-to-read-files-in-nodejs.md index 65a8a9a223357..6e2d70b37967f 100644 --- a/locale/pt-br/knowledge/file-system/how-to-read-files-in-nodejs.md +++ b/locale/pt-br/knowledge/file-system/how-to-read-files-in-nodejs.md @@ -9,10 +9,12 @@ layout: knowledge-post.hbs Ler o conteúdo de um arquivo na memória é uma tarefa muito comum na programação, e, como em muitas outras coisas, a API principal do Node.js fornece métodos para tornar isso trivial. Há uma variedade de métodos do sistema de arquivos, todos contidos no módulo `fs`. O modo mais fácil de ler todo o conteúdo de um arquivo é com `fs.readFile`, como segue: - fs = require('fs'); - fs.readFile(file, [encoding], [callback]); +```javascript +fs = require('fs'); +fs.readFile(file, [encoding], [callback]); - // file = (string) caminho do arquivo a ser lido +// file = (string) caminho do arquivo a ser lido +``` `encoding` é um parâmetro opcional que especifica o tipo de codificação para ler o arquivo. As codificações possíveis são 'ascii', 'utf8' e 'base64'. Se nenhuma codificação for fornecida, o valor padrão é `null`. @@ -20,34 +22,40 @@ Ler o conteúdo de um arquivo na memória é uma tarefa muito comum na programa Então, se nós quisermos ler o arquivo `/etc/hosts` e imprimí-lo no stdout (como o `cat` no UNIX): - fs = require('fs') - fs.readFile('/etc/hosts', 'utf8', function (err,data) { - if (err) { - return console.log(err); - } - console.log(data); - }); +```javascript +fs = require('fs') +fs.readFile('/etc/hosts', 'utf8', function (err,data) { + if (err) { + return console.log(err); + } + console.log(data); +}); +``` O conteúdo do `/etc/hosts` deve estar visível para você agora, desde que você tenha permissão para ler o arquivo em primeiro lugar. Vamos agora dar uma olhada em um exemplo do que acontece quando você tenta ler um arquivo inválido - o exemplo mais fácil é um arquivo que não existe. - fs = require('fs'); - fs.readFile('/doesnt/exist', 'utf8', function (err,data) { - if (err) { - return console.log(err); - } - console.log(data); - }); +```javascript +fs = require('fs'); +fs.readFile('/doesnt/exist', 'utf8', function (err,data) { + if (err) { + return console.log(err); + } + console.log(data); +}); +``` Esta é a saída: - { stack: [Getter/Setter], - arguments: undefined, - type: undefined, - message: 'ENOENT, No such file or directory \'/doesnt/exist\'', - errno: 2, - code: 'ENOENT', - path: '/doesnt/exist' } +``` +{ stack: [Getter/Setter], + arguments: undefined, + type: undefined, + message: 'ENOENT, No such file or directory \'/doesnt/exist\'', + errno: 2, + code: 'ENOENT', + path: '/doesnt/exist' } +``` Este é um [Error object](/pt-br/knowledge/errors/what-is-the-error-object/) básico do Node.js - muitas vezes pode ser útil logar diretamente `err.stack`, uma vez que ele contém uma stack trace para o local no código em que o objeto Error foi criado. diff --git a/locale/pt-br/knowledge/file-system/how-to-search-files-and-directories-in-nodejs.md b/locale/pt-br/knowledge/file-system/how-to-search-files-and-directories-in-nodejs.md index 118b1de5df215..a91afb45da364 100644 --- a/locale/pt-br/knowledge/file-system/how-to-search-files-and-directories-in-nodejs.md +++ b/locale/pt-br/knowledge/file-system/how-to-search-files-and-directories-in-nodejs.md @@ -9,33 +9,39 @@ layout: knowledge-post.hbs Suponha que você queira listar todos os arquivos no seu diretório atual. Uma abordagem é utilizar a [função](/pt-br/knowledge/file-system/how-to-read-files-in-nodejs/) builtin `fs.readdir`. Isto lhe retornará um array com todos os arquivos e diretórios do caminho especificado: - fs = require('fs'); - - fs.readdir(process.cwd(), function (err, files) { - if (err) { - console.log(err); - return; - } - console.log(files); - }); +```javascript +fs = require('fs'); + +fs.readdir(process.cwd(), function (err, files) { + if (err) { + console.log(err); + return; + } + console.log(files); +}); +``` Infelizmente, se você quiser fazer uma lista recursiva dos arquivos, então as coisas rapidamente ficarão muito mais complicadas. Para evitar toda essa complexidade assustadora, esta é uma das circunstâncias onde uma biblioteca feita por usuários pode salvar o dia. [Node-findit](https://github.com/substack/node-findit), pela SubStack, é um módulo auxiliar para facilitar a busca por arquivos. Ele tem interfaces para permitir você trabalhar com callbacks, eventos, ou simplesmente da velha forma síncrona (o que na maioria das vezes não é uma boa ideia). Para instalar `node-findit`, simplesmente use npm: - npm install findit +``` +npm install findit +``` Na mesma pasta, crie um arquivo chamado `example.js`, e então adicione este código. Execute-o com `node example.js`. Este exemplo usa o `node-findit` com a interface baseada em eventos. - //Isto instancia o localizador de arquivos - var finder = require('findit').find(__dirname); +```javascript +//Isto instancia o localizador de arquivos +var finder = require('findit').find(__dirname); - //Isto fica escutando por diretórios encontrados - finder.on('directory', function (dir) { - console.log('Directory: ' + dir + '/'); - }); +//Isto fica escutando por diretórios encontrados +finder.on('directory', function (dir) { + console.log('Directory: ' + dir + '/'); +}); - //Isto fica escutando por arquivos encontrados - finder.on('file', function (file) { - console.log('File: ' + file); - }); +//Isto fica escutando por arquivos encontrados +finder.on('file', function (file) { + console.log('File: ' + file); +}); +``` diff --git a/locale/pt-br/knowledge/file-system/how-to-store-local-config-data.md b/locale/pt-br/knowledge/file-system/how-to-store-local-config-data.md index 562f3a0b4e295..384356148518d 100644 --- a/locale/pt-br/knowledge/file-system/how-to-store-local-config-data.md +++ b/locale/pt-br/knowledge/file-system/how-to-store-local-config-data.md @@ -12,43 +12,47 @@ Armazenar os dados de configuração da sua aplicação Node.js é muito simples Vamos dar uma olhada em um exemplo muito simples (e imaginário). Primeiro, para salvar alguns dados bem simples: - var fs = require('fs'); - - var myOptions = { - name: 'Avian', - dessert: 'cake' - flavor: 'chocolate', - beverage: 'coffee' - }; - - var data = JSON.stringify(myOptions); - - fs.writeFile('./config.json', data, function (err) { - if (err) { - console.log('There has been an error saving your configuration data.'); - console.log(err.message); - return; - } - console.log('Configuration saved successfully.') - }); +```javascript +var fs = require('fs'); + +var myOptions = { + name: 'Avian', + dessert: 'cake' + flavor: 'chocolate', + beverage: 'coffee' +}; + +var data = JSON.stringify(myOptions); + +fs.writeFile('./config.json', data, function (err) { + if (err) { + console.log('There has been an error saving your configuration data.'); + console.log(err.message); + return; + } + console.log('Configuration saved successfully.') +}); +``` É realmente simples - apenas `JSON.stringify()` e então salve-o do jeito que você quiser. Agora, vamos carregar alguns dados de configuração: - var fs = require('fs'); +```javascript +var fs = require('fs'); - var data = fs.readFileSync('./config.json'), - myObj; +var data = fs.readFileSync('./config.json'), + myObj; - try { - myObj = JSON.parse(data); - console.dir(myObj); - } - catch (err) { - console.log('There has been an error parsing your JSON.') - console.log(err); - } +try { + myObj = JSON.parse(data); + console.dir(myObj); +} +catch (err) { + console.log('There has been an error parsing your JSON.') + console.log(err); +} +``` NODE PRO TIP: Mesmo que você não goste de usar `try/catch`, este é um lugar para usá-lo. `JSON.parse` é um analisador JSON muito rígido, e erros são comuns - mais importante, contudo, `JSON.parse` usa a declaração `throw` em vez de dar uma callback, então `try/catch` é o único jeito de se proteger contra os erros. @@ -56,27 +60,31 @@ Usar o método built-in `JSON` pode lhe levar longe, mas como tantos outros prob Vamos dar uma olhada agora em como nós realizaríamos acessos a algumas configurações locais com o `nconf`. Primeiro, você precisará instalá-lo no diretório do projeto: - npm install nconf +``` +npm install nconf +``` Após isso, a sintaxe é moleza. Veja um exemplo: - var nconf = require('nconf'); - - nconf.use('file', { file: './config.json' }); - nconf.load(); - nconf.set('name', 'Avian'); - nconf.set('dessert:name', 'Ice Cream'); - nconf.set('dessert:flavor', 'chocolate'); - - console.log(nconf.get('dessert')); - - nconf.save(function (err) { - if (err) { - console.error(err.message); - return; - } - console.log('Configuration saved successfully.'); - }); +```javascript +var nconf = require('nconf'); + +nconf.use('file', { file: './config.json' }); +nconf.load(); +nconf.set('name', 'Avian'); +nconf.set('dessert:name', 'Ice Cream'); +nconf.set('dessert:flavor', 'chocolate'); + +console.log(nconf.get('dessert')); + +nconf.save(function (err) { + if (err) { + console.error(err.message); + return; + } + console.log('Configuration saved successfully.'); +}); +``` A única coisa que requer atenção aqui é o delimitador - ':'. Quando se acessa propriedades aninhadas com o `nconf`, os dois-pontos são usados para delimitar os namespaces dos nomes das chaves. Se uma sub-chave específica não é fornecida, o objeto inteiro é definido ou retornado. diff --git a/locale/pt-br/knowledge/file-system/how-to-use-the-path-module.md b/locale/pt-br/knowledge/file-system/how-to-use-the-path-module.md index f937db48ac3ae..82a7ff0f9b4bb 100644 --- a/locale/pt-br/knowledge/file-system/how-to-use-the-path-module.md +++ b/locale/pt-br/knowledge/file-system/how-to-use-the-path-module.md @@ -12,22 +12,28 @@ O módulo path contém muitas funções auxiliares para ajudar a tornar a manipu A primeira função que vale a pena mencionar é `path.normalize`. Esta função pega um caminho (na forma de uma string) e remove barras duplicadas e normaliza abreviações de diretórios, como '.' para 'este diretório' e '..' para 'um diretório acima'. Por exemplo: - > var path = require('path'); - > path.normalize('/a/.///b/d/../c/') - '/a/b/c/' +``` +> var path = require('path'); +> path.normalize('/a/.///b/d/../c/') +'/a/b/c/' +``` Uma função intimamente relacionada a `normalize` é `join`. Esta função recebe um número variável de argumentos, junta-os, e normaliza o caminho. - > var path = require('path'); - > path.join('/a/.', './//b/', 'd/../c/') - '/a/b/c' +``` +> var path = require('path'); +> path.join('/a/.', './//b/', 'd/../c/') +'/a/b/c' +``` Um uso possível do `join` é para manipular caminhos quando servem urls: - > var path = require('path'); - > var url = '/index.html'; - > path.join(process.cwd(), 'static', url); - '/home/nico/static/index.html' +``` +> var path = require('path'); +> var url = '/index.html'; +> path.join(process.cwd(), 'static', url); +'/home/nico/static/index.html' +``` Há três funções que são usadas para extrair as várias partes do nome de um caminho: `basename`, `extname`, e `dirname`. - `basename` retorna o último pedaço do caminho recebido. @@ -35,21 +41,25 @@ Há três funções que são usadas para extrair as várias partes do nome de um - Finalmente, `dirname` retorna tudo que `basename` não retorna. Por exemplo: - > var path = require('path') - > var a = '/a/b/c.html' - > path.basename(a) - 'c.html' - > path.extname(a) - '.html' - > path.dirname(a) - '/a/b' +``` +> var path = require('path') +> var a = '/a/b/c.html' +> path.basename(a) +'c.html' +> path.extname(a) +'.html' +> path.dirname(a) +'/a/b' +``` Note que `basename` tem um segundo parâmetro opcional que extrairá a extensão se você passa a extensão correta. - > var path = require('path') - > var a = '/a/b/c.html' - > path.basename(a, path.extname(a)) - 'c' +``` +> var path = require('path') +> var a = '/a/b/c.html' +> path.basename(a, path.extname(a)) +'c' +``` Por último, o módulo `path` fornece métodos para checar se um determinado caminho existe ou não: `exists` e `existsSync` Os dois recebem o caminho de um arquivo como primeiro parâmetro. @@ -59,9 +69,11 @@ Por último, o módulo `path` fornece métodos para checar se um determinado cam Bloqueio nem sempre é uma coisa ruim. Checar a existência de um arquivo de configuração essencial de forma síncrona faz sentido, por exemplo - não interessa muito se seu processo está bloqueado por algo que ele não pode viver sem! Por outro lado, entretanto, em um servidor HTTP muito ativo, qualquer entrada/saída de arquivos por requisição **DEVE** ser assíncrona, senão você responderá as requisições uma por uma. Veja o artigo em [operações assíncronas](/en/knowledge/getting-started/control-flow/how-to-write-asynchronous-code/) para mais detalhes. - > var path = require('path') - > path.exists('/etc', function(exists){console.log("Does the file exist?", exists)}) - > Does the file exist? true +``` +> var path = require('path') +> path.exists('/etc', function(exists){console.log("Does the file exist?", exists)}) +> Does the file exist? true - > path.existsSync('/etc') - true +> path.existsSync('/etc') +true +``` diff --git a/locale/pt-br/knowledge/file-system/how-to-write-files-in-nodejs.md b/locale/pt-br/knowledge/file-system/how-to-write-files-in-nodejs.md index 69be22720b638..b5cd094009999 100644 --- a/locale/pt-br/knowledge/file-system/how-to-write-files-in-nodejs.md +++ b/locale/pt-br/knowledge/file-system/how-to-write-files-in-nodejs.md @@ -9,8 +9,10 @@ layout: knowledge-post.hbs Escrever em um arquivo é outra das tarefas básicas da programação que um desenvolvedor normalmente precisa conhecer - por sorte, esta tarefa é muito simples no Node.js. Nós podemos usar o conveniente método `writeFile` do módulo `fs` da biblioteca padrão, que pode evitar todo tipo de problemas e economizar tempo. - fs = require('fs'); - fs.writeFile(filename, data, [encoding], [callback]) +```javascript +fs = require('fs'); +fs.writeFile(filename, data, [encoding], [callback]) +``` `file = (string)` caminho do arquivo a ser lido @@ -22,29 +24,37 @@ Escrever em um arquivo é outra das tarefas básicas da programação que um des Então, se nós quisermos escrever "Hello World" em `helloworld.txt`: - fs = require('fs'); - fs.writeFile('helloworld.txt', 'Hello World!', function (err) { - if (err) return console.log(err); - console.log('Hello World > helloworld.txt'); - }); +```javascript +fs = require('fs'); +fs.writeFile('helloworld.txt', 'Hello World!', function (err) { + if (err) return console.log(err); + console.log('Hello World > helloworld.txt'); +}); +``` - [conteúdo de helloworld.txt]: - Hello World! +``` +[conteúdo de helloworld.txt]: +Hello World! +``` Se nós propositalmente quisermos causar um erro, podemos tentar escrever em um arquivo que nós não temos permissão de acesso: - fs = require('fs') - fs.writeFile('/etc/doesntexist', 'abc', function (err,data) { - if (err) { - return console.log(err); - } - console.log(data); - }); - - { stack: [Getter/Setter], - arguments: undefined, - type: undefined, - message: 'EACCES, Permission denied \'/etc/doesntexist\'', - errno: 13, - code: 'EACCES', - path: '/etc/doesntexist' } +```javascript +fs = require('fs') +fs.writeFile('/etc/doesntexist', 'abc', function (err,data) { + if (err) { + return console.log(err); + } + console.log(data); +}); +``` + +``` +{ stack: [Getter/Setter], + arguments: undefined, + type: undefined, + message: 'EACCES, Permission denied \'/etc/doesntexist\'', + errno: 13, + code: 'EACCES', + path: '/etc/doesntexist' } +``` diff --git a/locale/pt-br/knowledge/file-system/security/introduction.md b/locale/pt-br/knowledge/file-system/security/introduction.md index 16fc8de229d0f..f8edc44de79ad 100644 --- a/locale/pt-br/knowledge/file-system/security/introduction.md +++ b/locale/pt-br/knowledge/file-system/security/introduction.md @@ -14,17 +14,21 @@ layout: knowledge-post.hbs Poison null bytes é um modo de enganar o seu código para que ele veja outro nome de arquivo em vez do que realmente está sendo aberto. Isto pode, em muitos casos, ser usado para contornar proteções a directory traversal, para enganar servidores a entregar arquivos com tipos errados e para contornar restrições nos nomes de arquivos que podem ser usados. [Aqui está uma descrição mais detalhada.](http://groups.google.com/group/nodejs/browse_thread/thread/51f66075e249d767/85f647474b564fde) Sempre use código como este quando estiver acessando arquivos com nomes fornecidos pelo usuário: - if (filename.indexOf('\0') !== -1) { - return respond('That was evil.'); - } +```javascript +if (filename.indexOf('\0') !== -1) { + return respond('That was evil.'); +} +``` ## Whitelisting Você nem sempre será capaz de usar whitelisting, mas se for, é muito fácil de implementar e difícil de dar errado. Por exemplo, se você souber que todos os nomes de arquivos são strings alfanuméricas em caixa baixa: - if (!/^[a-z0-9]+$/.test(filename)) { - return respond('illegal character'); - } +```javascript +if (!/^[a-z0-9]+$/.test(filename)) { + return respond('illegal character'); +} +``` Contudo, note que whitelisting sozinha não será suficiente assim que você permitir pontos e barras - pessoas poderiam entrar com coisas como `../../etc/passwd` a fim de obter arquivos de fora da pasta permitida. @@ -34,17 +38,23 @@ Directory traversal significa que um atacante tenta acessar arquivos fora do dir Este exemplo assume que você já checou a variável `userSuppliedFilename` como descrito na seção acima "Poison Null Bytes". - var rootDirectory = '/var/www/'; +```javascript +var rootDirectory = '/var/www/'; +``` Garanta que você tem uma barra no final do nome dos diretórios permitidos - você não quer que pessoas sejam capazes de acessar `/var/www-secret/`, não é?. - var path = require('path'); - var filename = path.join(rootDirectory, userSuppliedFilename); +```javascript +var path = require('path'); +var filename = path.join(rootDirectory, userSuppliedFilename); +``` Agora `filename` contém um caminho absoluto e não contém mais sequências `..` - `path.join` cuida disso. Entretanto, pode ser algo como `/etc/passwd` agora, aí você tem que checar se começa com `rootDirectory`: - if (filename.indexOf(rootDirectory) !== 0) { - return respond('trying to sneak out of the web root?'); - } +```javascript +if (filename.indexOf(rootDirectory) !== 0) { + return respond('trying to sneak out of the web root?'); +} +``` Agora a varável `filename` deve conter o nome do arquivo ou diretório que está dentro do diretório permitido (a menos que ele não exista). diff --git a/locale/pt-br/knowledge/getting-started/how-to-use-util-inspect.md b/locale/pt-br/knowledge/getting-started/how-to-use-util-inspect.md index 33c044de65296..cb768dd3d2dd9 100644 --- a/locale/pt-br/knowledge/getting-started/how-to-use-util-inspect.md +++ b/locale/pt-br/knowledge/getting-started/how-to-use-util-inspect.md @@ -8,81 +8,55 @@ difficulty: 1 layout: knowledge-post.hbs --- - - O Node oferece uma função utilitária, para fins de depuração, que retorna uma representação string de um objeto. `util.inspect()` pode ser de grande ajuda quando utilizada com propriedades de objetos que são muito grandes ou complexos. Vamos ver um exemplo simples. `util.inspect()` pode ser usado em qualquer objeto - uma boa demonstração será utilizá-la em um dos objetos internos do Node. Tente isso no REPL (digite `node` na sua linha de comando, sem argumentos): - var util = require('util'); - util.inspect(console); - - +```javascript +var util = require('util'); +util.inspect(console); +``` O resultado vai ser: - '{ log: [Function], info: [Function], warn: [Function], error: [Function], dir: [Function], time: [Function], timeEnd: [Function], trace: [Function], assert: [Function] }' +``` +'{ log: [Function], info: [Function], warn: [Function], error: [Function], dir: [Function], time: [Function], timeEnd: [Function], trace: [Function], assert: [Function] }' +``` Esta é uma listagem de todas as propriedades enumeráveis ​​do objeto `console`. Também vale a pena notar que `console.dir` é um wrapper em torno de `util.inspect` que utiliza seus argumentos padrões. - - No REPL, `util.inspect` retornará imediatamente seu resultado - esse não é o caso normalmente. No contexto de um código Node.js comum em um arquivo, algo deve ser feito com o resultado. A coisa mais simples a fazer: - console.log(util.inspect(myObj)); +```javascript +console.log(util.inspect(myObj)); +``` `util.inspect` pode também receber diversos argumentos opcionais, mostrados aqui com seus valores padrões: - util.inspect(object, showHidden=false, depth=2, colorize=true); - - +```javascript +util.inspect(object, showHidden=false, depth=2, colorize=true); +``` Por exemplo, `util.inspect(myObj, true, 7, true)` inspecionaria `myObj`, mostrando todas as propriedades ocultas e não ocultas até uma profundidade de `7` e coloriria o resultado. Vamos conferir os argumentos individualmente. O argumento `depth` representa o número de níveis dentro de um objeto aninhado para ser recursivo - o padrão é 2. Configurá-lo para `null` fará com que ele vá até o último nível, mostrando todos os níveis. Compare o tamanho dos resultados dessas duas instruções `util.inspect` no REPL: - var http = require('http'); - util.inspect(http, true, 1); - util.inspect(http, true, 3); - - +```javascript +var http = require('http'); +util.inspect(http, true, 1); +util.inspect(http, true, 3); +``` O argumento opcional `showHidden` é um booleano que determina se as propriedades 'não-enumeráveis' de um objeto serão ou não exibidas - o padrão é `false`, o que tende a resultar em uma saída muito mais legível. Isso não é algo que um iniciante precise se preocupar na maior parte do tempo, mas vale a pena demonstrar brevemente. Mais uma vez, tente o seguinte no REPL: - var util = require('util'); - util.inspect(console, true); - - +```javascript +var util = require('util'); +util.inspect(console, true); +``` Finalmente, o argumento opcional `colorize` é um booleano que adiciona códigos de escape ANSI ao resultado da string. Quando utilizado em uma janela de terminal, o resultado deve aparecer colorido. - var util = require('util'); - console.log(util.inspect({a:1, b:"b"}, false,2,true)); +```javascript +var util = require('util'); +console.log(util.inspect({a:1, b:"b"}, false,2,true)); +``` diff --git a/locale/pt-br/knowledge/getting-started/npm/what-is-npm.md b/locale/pt-br/knowledge/getting-started/npm/what-is-npm.md index 235a44c268002..6ec27ffecec6d 100644 --- a/locale/pt-br/knowledge/getting-started/npm/what-is-npm.md +++ b/locale/pt-br/knowledge/getting-started/npm/what-is-npm.md @@ -17,8 +17,10 @@ Outro uso importante do npm é o gerenciamento de dependências. Quando você te Exemplo: - git clone https://github.com/cloudhead/vows.git - cd vows - npm install +``` +git clone https://github.com/cloudhead/vows.git +cd vows +npm install +``` Após executar estes comandos, você verá o diretório `node_modules` contendo todas as dependências do projeto especificadas em package.json. diff --git a/locale/pt-br/knowledge/getting-started/what-is-require.md b/locale/pt-br/knowledge/getting-started/what-is-require.md index ced53a3c9d647..f78b79b128fc8 100644 --- a/locale/pt-br/knowledge/getting-started/what-is-require.md +++ b/locale/pt-br/knowledge/getting-started/what-is-require.md @@ -12,44 +12,52 @@ layout: knowledge-post.hbs O Node.js segue o sistema de módulos CommomJS, e a função nativa `require` é a forma mais fácil de incluir módulos que existem em arquivos separados. A funcionalidade básica do `require` é que ele lê um arquivo javascript, executa o arquivo e então retorna o objeto `exports`. Um exemplo de módulo: - console.log("evaluating example.js"); +```javascript +console.log("evaluating example.js"); - var invisible = function () { - console.log("invisible"); - } +var invisible = function () { + console.log("invisible"); +} - exports.message = "hi"; +exports.message = "hi"; - exports.say = function () { - console.log(exports.message); - } +exports.say = function () { + console.log(exports.message); +} +``` - Então, se você executar `var example = require('./example.js')`, então o `example.js` será processado e, em seguida, `example` será um objeto igual a: +Então, se você executar `var example = require('./example.js')`, então o `example.js` será processado e, em seguida, `example` será um objeto igual a: - { - message: "hi", - say: [Function] - } +``` +{ + message: "hi", + say: [Function] +} +``` Se você quiser definir o objeto exportado para uma função ou um novo objeto, você tem que usar o objeto `module.exports`. Então, por exemplo: - module.exports = function () { - console.log("hello world") - } +```javascript +module.exports = function () { + console.log("hello world") +} - require('./example2.js')() //requere ele mesmo e executa o objeto exportado. +require('./example2.js')() //requere ele mesmo e executa o objeto exportado. +``` Vale a pena notar que cada vez que você subseqüentemente requere um arquivo já requerido, o objeto `exports` é armazenado em cache e reutilizado. Para ilustrar este ponto: - node> require('./example.js') - avaliando example.js - { message: 'hi', say: [Function] } - node> require('./example.js') - { message: 'hi', say: [Function] } - node> require('./example.js').message = "hey" //atribuindo "hey" para message - 'hey' - node> require('./example.js') //Pode-se pensar que isso "recarregaria" o arquivo... - { message: 'hey', say: [Function] } //...mas a mensagem ainda é "hey" devido ao cache do módulo. +``` +node> require('./example.js') +avaliando example.js +{ message: 'hi', say: [Function] } +node> require('./example.js') +{ message: 'hi', say: [Function] } +node> require('./example.js').message = "hey" //atribuindo "hey" para message +'hey' +node> require('./example.js') //Pode-se pensar que isso "recarregaria" o arquivo... +{ message: 'hey', say: [Function] } //...mas a mensagem ainda é "hey" devido ao cache do módulo. +``` Como você pode ver acima, `example.js` é processado na primeira vez, mas todas as chamadas subsequentes para o `require()` invocam apenas o cache do módulo, em vez de ler o arquivo novamente. E como visto acima, isso pode ocasionalmente produzir efeitos colaterais. diff --git a/locale/ru/knowledge/file-system/how-to-read-files-in-nodejs.md b/locale/ru/knowledge/file-system/how-to-read-files-in-nodejs.md index 1c78ddf08fe91..baee48d7296fc 100644 --- a/locale/ru/knowledge/file-system/how-to-read-files-in-nodejs.md +++ b/locale/ru/knowledge/file-system/how-to-read-files-in-nodejs.md @@ -9,10 +9,12 @@ layout: knowledge-post.hbs Чтение содержимого файла ― очень распространенная задача программирования, и, как и для многих других вещей, базовый API Node.js предоставляет методы, позволяющие упростить эту задачу. Существует множество методов файловой системы, все они содержатся в модуле `fs`. Что бы прочитать всё содержимое файла, проще всего использовать `fs.readFile`. Выглядит это следующим образом: - fs = require('fs'); - fs.readFile(file, [encoding], [callback]); +```javascript +fs = require('fs'); +fs.readFile(file, [encoding], [callback]); - // file = (string) путь к файлу, который нужно прочитать +// file = (string) путь к файлу, который нужно прочитать +``` `encoding` это необязательный параметр, который указывает тип кодировки, для чтения файла. Возможные кодировки: 'ascii', 'utf8' и 'base64'. Если кодировка не указана, по умолчанию используется значение `null`. @@ -20,34 +22,40 @@ layout: knowledge-post.hbs Поэтому, если мы хотим прочитать `/etc/hosts` и вывести его в stdout (точно так же, как `cat` в UNIX): - fs = require('fs') - fs.readFile('/etc/hosts', 'utf8', function (err,data) { - if (err) { - return console.log(err); - } - console.log(data); - }); +```javascript +fs = require('fs') +fs.readFile('/etc/hosts', 'utf8', function (err,data) { + if (err) { + return console.log(err); + } + console.log(data); +}); +``` Содержимое `/etc/hosts` теперь должно быть видно вам, но при условии, что у вас есть разрешение на чтение файла. Давайте теперь рассмотрим пример того, что происходит, когда вы пытаетесь прочитать недопустимый файл ― самый простой пример ― несуществующий файл. - fs = require('fs'); - fs.readFile('/несуществующий/файл', 'utf8', function (err,data) { - if (err) { - return console.log(err); - } - console.log(data); - }); +```javascript +fs = require('fs'); +fs.readFile('/несуществующий/файл', 'utf8', function (err,data) { + if (err) { + return console.log(err); + } + console.log(data); +}); +``` Это вывод: - { stack: [Getter/Setter], - arguments: undefined, - type: undefined, - message: 'ENOENT, No such file or directory \'/несуществующий/файл\'', - errno: 2, - code: 'ENOENT', - path: '/несуществующий/файл' } +``` +{ stack: [Getter/Setter], + arguments: undefined, + type: undefined, + message: 'ENOENT, No such file or directory \'/несуществующий/файл\'', + errno: 2, + code: 'ENOENT', + path: '/несуществующий/файл' } +``` Это базовый [Error object](/en/knowledge/errors/what-is-the-error-object/) Node.js ― часто может быть полезно вызывать `err.stack` напрямую, поскольку он содержит трассировку стека до места в коде, в котором был создан Error object.