From 19ff8071fd766f26362562ab77590c064c12bae4 Mon Sep 17 00:00:00 2001 From: Vse Mozhet Byt Date: Fri, 21 Apr 2017 17:38:31 +0300 Subject: [PATCH] doc: conform to rules for eslint-plugin-markdown Backport-PR-URL: https://github.com/nodejs/node/pull/14067 PR-URL: https://github.com/nodejs/node/pull/12563 Refs: https://github.com/nodejs/node/pull/12557#issuecomment-296015032 Reviewed-By: Teddy Katz Reviewed-By: James M Snell Reviewed-By: Timothy Gu Reviewed-By: Gibson Fahnestock Reviewed-By: Yuta Hiroto --- benchmark/README.md | 39 +++++----- doc/api/assert.md | 35 ++++----- doc/api/buffer.md | 16 ++-- doc/api/child_process.md | 12 ++- doc/api/cluster.md | 13 ++-- doc/api/console.md | 6 +- doc/api/crypto.md | 6 +- doc/api/debugger.md | 1 + doc/api/dgram.md | 4 +- doc/api/dns.md | 3 + doc/api/domain.md | 2 +- doc/api/fs.md | 2 +- doc/api/http.md | 43 ++++++----- doc/api/modules.md | 9 +-- doc/api/net.md | 2 + doc/api/os.md | 2 + doc/api/path.md | 78 ++++++++++---------- doc/api/process.md | 39 +++++----- doc/api/querystring.md | 9 ++- doc/api/readline.md | 2 +- doc/api/repl.md | 21 ++++-- doc/api/stream.md | 50 ++++++------- doc/api/url.md | 6 +- doc/api/util.md | 9 ++- doc/api/v8.md | 1 + doc/api/vm.md | 17 +++-- doc/api/zlib.md | 33 +++++---- doc/guides/timers-in-node.md | 14 ++-- doc/guides/writing-tests.md | 23 +++--- doc/topics/domain-postmortem.md | 14 ++-- doc/topics/event-loop-timers-and-nexttick.md | 59 ++++++++------- tools/icu/README.md | 8 +- 32 files changed, 311 insertions(+), 267 deletions(-) diff --git a/benchmark/README.md b/benchmark/README.md index c3d950f792e31f..b63c14fb072f80 100644 --- a/benchmark/README.md +++ b/benchmark/README.md @@ -34,17 +34,18 @@ constructor iterates through the configuration object property values and runs the test function with each of the combined arguments in spawned processes. For example, buffers/buffer-read.js has the following configuration: + ```js var bench = common.createBenchmark(main, { noAssert: [false, true], buffer: ['fast', 'slow'], type: ['UInt8', 'UInt16LE', 'UInt16BE', - 'UInt32LE', 'UInt32BE', - 'Int8', 'Int16LE', 'Int16BE', - 'Int32LE', 'Int32BE', - 'FloatLE', 'FloatBE', - 'DoubleLE', 'DoubleBE'], - millions: [1] + 'UInt32LE', 'UInt32BE', + 'Int8', 'Int16LE', 'Int16BE', + 'Int32LE', 'Int32BE', + 'FloatLE', 'FloatBE', + 'DoubleLE', 'DoubleBE'], + millions: [1] }); ``` The runner takes one item from each of the property array value to build a list @@ -52,21 +53,24 @@ of arguments to run the main function. The main function will receive the conf object as follows: - first run: + + ```js - { noAssert: false, - buffer: 'fast', - type: 'UInt8', - millions: 1 - } +{ noAssert: false, + buffer: 'fast', + type: 'UInt8', + millions: 1 +} ``` - second run: + + ```js - { - noAssert: false, - buffer: 'fast', - type: 'UInt16LE', - millions: 1 - } +{ noAssert: false, + buffer: 'fast', + type: 'UInt16LE', + millions: 1 +} ``` ... @@ -122,6 +126,7 @@ buffers/buffer-slice.js. ### The code snippet + ```js var common = require('../common.js'); // Load the test runner diff --git a/doc/api/assert.md b/doc/api/assert.md index e02829918c8b45..0b7621520b688f 100644 --- a/doc/api/assert.md +++ b/doc/api/assert.md @@ -43,18 +43,18 @@ are evaluated also: const assert = require('assert'); const obj1 = { - a : { - b : 1 + a: { + b: 1 } }; const obj2 = { - a : { - b : 2 + a: { + b: 2 } }; const obj3 = { - a : { - b : 1 + a: { + b: 1 } }; const obj4 = Object.create(obj1); @@ -93,10 +93,10 @@ Second, object comparisons include a strict equality check of their prototypes. ```js const assert = require('assert'); -assert.deepEqual({a:1}, {a:'1'}); +assert.deepEqual({ a: 1 }, { a: '1' }); // OK, because 1 == '1' -assert.deepStrictEqual({a:1}, {a:'1'}); +assert.deepStrictEqual({ a: 1 }, { a: '1' }); // AssertionError: { a: 1 } deepStrictEqual { a: '1' } // because 1 !== '1' using strict equality ``` @@ -251,18 +251,18 @@ Tests for any deep inequality. Opposite of [`assert.deepEqual()`][]. const assert = require('assert'); const obj1 = { - a : { - b : 1 + a: { + b: 1 } }; const obj2 = { - a : { - b : 2 + a: { + b: 2 } }; const obj3 = { - a : { - b : 1 + a: { + b: 1 } }; const obj4 = Object.create(obj1); @@ -297,10 +297,10 @@ Tests for deep strict inequality. Opposite of [`assert.deepStrictEqual()`][]. ```js const assert = require('assert'); -assert.notDeepEqual({a:1}, {a:'1'}); +assert.notDeepEqual({a: 1}, {a: '1'}); // AssertionError: { a: 1 } notDeepEqual { a: '1' } -assert.notDeepStrictEqual({a:1}, {a:'1'}); +assert.notDeepStrictEqual({a: 1}, {a: '1'}); // OK ``` @@ -466,7 +466,7 @@ assert.throws( throw new Error('Wrong value'); }, function(err) { - if ( (err instanceof Error) && /value/.test(err) ) { + if ((err instanceof Error) && /value/.test(err)) { return true; } }, @@ -478,6 +478,7 @@ Note that `error` can not be a string. If a string is provided as the second argument, then `error` is assumed to be omitted and the string will be used for `message` instead. This can lead to easy-to-miss mistakes: + ```js // THIS IS A MISTAKE! DO NOT DO THIS! assert.throws(myFunction, 'missing foo', 'did not throw with expected message'); diff --git a/doc/api/buffer.md b/doc/api/buffer.md index b89135bbdcba59..69e800ae09e761 100644 --- a/doc/api/buffer.md +++ b/doc/api/buffer.md @@ -886,7 +886,7 @@ Example: Copy an ASCII string into a `Buffer`, one byte at a time const str = 'Node.js'; const buf = Buffer.allocUnsafe(str.length); -for (let i = 0; i < str.length ; i++) { +for (let i = 0; i < str.length; i++) { buf[i] = str.charCodeAt(i); } @@ -994,7 +994,7 @@ byte 16 through byte 19 into `buf2`, starting at the 8th byte in `buf2` const buf1 = Buffer.allocUnsafe(26); const buf2 = Buffer.allocUnsafe(26).fill('!'); -for (let i = 0 ; i < 26 ; i++) { +for (let i = 0; i < 26; i++) { // 97 is the decimal ASCII value for 'a' buf1[i] = i + 97; } @@ -1011,7 +1011,7 @@ overlapping region within the same `Buffer` ```js const buf = Buffer.allocUnsafe(26); -for (let i = 0 ; i < 26 ; i++) { +for (let i = 0; i < 26; i++) { // 97 is the decimal ASCII value for 'a' buf[i] = i + 97; } @@ -1781,7 +1781,7 @@ one byte from the original `Buffer` ```js const buf1 = Buffer.allocUnsafe(26); -for (let i = 0 ; i < 26 ; i++) { +for (let i = 0; i < 26; i++) { // 97 is the decimal ASCII value for 'a' buf1[i] = i + 97; } @@ -1930,7 +1930,7 @@ Examples: ```js const buf1 = Buffer.allocUnsafe(26); -for (let i = 0 ; i < 26 ; i++) { +for (let i = 0; i < 26; i++) { // 97 is the decimal ASCII value for 'a' buf1[i] = i + 97; } @@ -1974,9 +1974,9 @@ const json = JSON.stringify(buf); console.log(json); const copy = JSON.parse(json, (key, value) => { - return value && value.type === 'Buffer' - ? Buffer.from(value.data) - : value; + return value && value.type === 'Buffer' ? + Buffer.from(value.data) : + value; }); // Prints: diff --git a/doc/api/child_process.md b/doc/api/child_process.md index 3ea65c6fcb0d04..11c40f425fd93e 100644 --- a/doc/api/child_process.md +++ b/doc/api/child_process.md @@ -188,7 +188,7 @@ the process is spawned. The default options are: const defaults = { encoding: 'utf8', timeout: 0, - maxBuffer: 200*1024, + maxBuffer: 200 * 1024, killSignal: 'SIGTERM', cwd: null, env: null @@ -868,13 +868,17 @@ as in this example: 'use strict'; const spawn = require('child_process').spawn; -const child = spawn('sh', ['-c', - `node -e "setInterval(() => { +const child = spawn( + 'sh', + [ + '-c', + `node -e "setInterval(() => { console.log(process.pid, 'is alive') }, 500);"` ], { stdio: ['inherit', 'inherit', 'inherit'] - }); + } +); setTimeout(() => { child.kill(); // does not terminate the node process in the shell diff --git a/doc/api/cluster.md b/doc/api/cluster.md index bdf58e2b45f279..1d605503848963 100644 --- a/doc/api/cluster.md +++ b/doc/api/cluster.md @@ -511,11 +511,14 @@ When any of the workers die the cluster module will emit the `'exit'` event. This can be used to restart the worker by calling `.fork()` again. ```js -cluster.on('exit', (worker, code, signal) => { - console.log('worker %d died (%s). restarting...', - worker.process.pid, signal || code); - cluster.fork(); -}); +cluster.on( + 'exit', + (worker, code, signal) => { + console.log('worker %d died (%s). restarting...', + worker.process.pid, signal || code); + cluster.fork(); + } +); ``` See [child_process event: 'exit'][]. diff --git a/doc/api/console.md b/doc/api/console.md index 95a8924f8c9a05..5b687140253d26 100644 --- a/doc/api/console.md +++ b/doc/api/console.md @@ -130,7 +130,7 @@ the default behavior of `console` in Node.js. // new impl for assert without monkey-patching. const myConsole = Object.create(console, { assert: { - value: function assert(assertion, message, ...args) { + value(assertion, message, ...args) { try { console.assert(assertion, message, ...args); } catch (err) { @@ -253,9 +253,7 @@ prints the result to `stdout`: ```js console.time('100-elements'); -for (let i = 0; i < 100; i++) { - ; -} +for (let i = 0; i < 100; i++) ; console.timeEnd('100-elements'); // prints 100-elements: 225.438ms ``` diff --git a/doc/api/crypto.md b/doc/api/crypto.md index 0f0062ae2fce71..0af112727b3f65 100644 --- a/doc/api/crypto.md +++ b/doc/api/crypto.md @@ -280,7 +280,8 @@ decipher.on('end', () => { // Prints: some clear text data }); -const encrypted = 'ca981be48e90867604588e75d04feabb63cc007a8f8ad89b10616ed84d815504'; +const encrypted = + 'ca981be48e90867604588e75d04feabb63cc007a8f8ad89b10616ed84d815504'; decipher.write(encrypted, 'hex'); decipher.end(); ``` @@ -304,7 +305,8 @@ Example: Using the [`decipher.update()`][] and [`decipher.final()`][] methods: const crypto = require('crypto'); const decipher = crypto.createDecipher('aes192', 'a password'); -const encrypted = 'ca981be48e90867604588e75d04feabb63cc007a8f8ad89b10616ed84d815504'; +const encrypted = + 'ca981be48e90867604588e75d04feabb63cc007a8f8ad89b10616ed84d815504'; let decrypted = decipher.update(encrypted, 'hex', 'utf8'); decrypted += decipher.final('utf8'); console.log(decrypted); diff --git a/doc/api/debugger.md b/doc/api/debugger.md index 745c5ac5b451b9..1c9b1049e82491 100644 --- a/doc/api/debugger.md +++ b/doc/api/debugger.md @@ -26,6 +26,7 @@ inspection are possible. Inserting the statement `debugger;` into the source code of a script will enable a breakpoint at that position in the code: + ```js // myscript.js global.x = 5; diff --git a/doc/api/dgram.md b/doc/api/dgram.md index 2d996ce0c6b058..2aec4abb254643 100644 --- a/doc/api/dgram.md +++ b/doc/api/dgram.md @@ -20,7 +20,7 @@ server.on('message', (msg, rinfo) => { }); server.on('listening', () => { - var address = server.address(); + const address = server.address(); console.log(`server listening ${address.address}:${address.port}`); }); @@ -146,7 +146,7 @@ server.on('message', (msg, rinfo) => { }); server.on('listening', () => { - var address = server.address(); + const address = server.address(); console.log(`server listening ${address.address}:${address.port}`); }); diff --git a/doc/api/dns.md b/doc/api/dns.md index 811ad84e016edd..457559d0ce692c 100644 --- a/doc/api/dns.md +++ b/doc/api/dns.md @@ -268,6 +268,7 @@ will contain an array of objects with the following properties: For example: + ```js { flags: 's', @@ -306,6 +307,7 @@ be an object with the following properties: * `expire` * `minttl` + ```js { nsname: 'ns.example.com', @@ -332,6 +334,7 @@ be an array of objects with the following properties: * `port` * `name` + ```js { priority: 10, diff --git a/doc/api/domain.md b/doc/api/domain.md index 1cc25e0cf8d8fb..e98ccc87a0e346 100644 --- a/doc/api/domain.md +++ b/doc/api/domain.md @@ -162,7 +162,7 @@ function handleRequest(req, res) { setTimeout(() => { // Whoops! flerb.bark(); - }); + }, timeout); break; default: res.end('ok'); diff --git a/doc/api/fs.md b/doc/api/fs.md index 76cffbef4f05a3..56969fc1d67dff 100644 --- a/doc/api/fs.md +++ b/doc/api/fs.md @@ -218,7 +218,7 @@ synchronous counterparts are of this type. For a regular file [`util.inspect(stats)`][] would return a string very similar to this: -```txt +``` Stats { dev: 2114, ino: 48064969, diff --git a/doc/api/http.md b/doc/api/http.md index 02b7aa5cc9e7e7..faefc803f7004b 100644 --- a/doc/api/http.md +++ b/doc/api/http.md @@ -12,6 +12,7 @@ user is able to stream data. HTTP message headers are represented by an object like this: + ```js { 'content-length': '123', 'content-type': 'text/plain', @@ -34,6 +35,7 @@ property, which is an array of `[key, value, key2, value2, ...]`. For example, the previous message header object might have a `rawHeaders` list like the following: + ```js [ 'ConTent-Length', '123456', 'content-LENGTH', '123', @@ -130,7 +132,7 @@ To configure any of them, you must create your own [`http.Agent`][] instance. ```js const http = require('http'); -var keepAliveAgent = new http.Agent({ keepAlive: true }); +const keepAliveAgent = new http.Agent({ keepAlive: true }); options.agent = keepAliveAgent; http.request(options, onResponseCallback); ``` @@ -309,14 +311,14 @@ const net = require('net'); const url = require('url'); // Create an HTTP tunneling proxy -var proxy = http.createServer( (req, res) => { +const proxy = http.createServer((req, res) => { res.writeHead(200, {'Content-Type': 'text/plain'}); res.end('okay'); }); proxy.on('connect', (req, cltSocket, head) => { // connect to an origin server - var srvUrl = url.parse(`http://${req.url}`); - var srvSocket = net.connect(srvUrl.port, srvUrl.hostname, () => { + const srvUrl = url.parse(`http://${req.url}`); + const srvSocket = net.connect(srvUrl.port, srvUrl.hostname, () => { cltSocket.write('HTTP/1.1 200 Connection Established\r\n' + 'Proxy-agent: Node.js-Proxy\r\n' + '\r\n'); @@ -330,14 +332,14 @@ proxy.on('connect', (req, cltSocket, head) => { proxy.listen(1337, '127.0.0.1', () => { // make a request to a tunneling proxy - var options = { + const options = { port: 1337, hostname: '127.0.0.1', method: 'CONNECT', path: 'www.google.com:80' }; - var req = http.request(options); + const req = http.request(options); req.end(); req.on('connect', (res, socket, head) => { @@ -405,7 +407,7 @@ A client server pair that show you how to listen for the `'upgrade'` event. const http = require('http'); // Create an HTTP server -var srv = http.createServer( (req, res) => { +const srv = http.createServer((req, res) => { res.writeHead(200, {'Content-Type': 'text/plain'}); res.end('okay'); }); @@ -422,7 +424,7 @@ srv.on('upgrade', (req, socket, head) => { srv.listen(1337, '127.0.0.1', () => { // make a request - var options = { + const options = { port: 1337, hostname: '127.0.0.1', headers: { @@ -431,7 +433,7 @@ srv.listen(1337, '127.0.0.1', () => { } }; - var req = http.request(options); + const req = http.request(options); req.end(); req.on('upgrade', (res, socket, upgradeHead) => { @@ -933,7 +935,7 @@ Note that the name is case insensitive. Example: ```js -var contentType = response.getHeader('content-type'); +const contentType = response.getHeader('content-type'); ``` ### response.headersSent @@ -1006,7 +1008,7 @@ any headers passed to [`response.writeHead()`][], with the headers passed to ```js // returns content-type = text/plain -const server = http.createServer((req,res) => { +const server = http.createServer((req, res) => { res.setHeader('Content-Type', 'text/html'); res.setHeader('X-Foo', 'bar'); res.writeHead(200, {'Content-Type': 'text/plain'}); @@ -1138,7 +1140,7 @@ argument. Example: ```js -var body = 'hello world'; +const body = 'hello world'; response.writeHead(200, { 'Content-Length': Buffer.byteLength(body), 'Content-Type': 'text/plain' }); @@ -1156,7 +1158,7 @@ any headers passed to [`response.writeHead()`][], with the headers passed to ```js // returns content-type = text/plain -const server = http.createServer((req,res) => { +const server = http.createServer((req, res) => { res.setHeader('Content-Type', 'text/html'); res.setHeader('X-Foo', 'bar'); res.writeHead(200, {'Content-Type': 'text/plain'}); @@ -1385,6 +1387,7 @@ Accept: text/plain\r\n Then `request.url` will be: + ```js '/status?name=ryan' ``` @@ -1488,10 +1491,10 @@ http.get('http://nodejs.org/dist/index.json', (res) => { let error; if (statusCode !== 200) { - error = new Error(`Request Failed.\n` + + error = new Error('Request Failed.\n' + `Status Code: ${statusCode}`); } else if (!/^application\/json/.test(contentType)) { - error = new Error(`Invalid content-type.\n` + + error = new Error('Invalid content-type.\n' + `Expected application/json but received ${contentType}`); } if (error) { @@ -1506,7 +1509,7 @@ http.get('http://nodejs.org/dist/index.json', (res) => { res.on('data', (chunk) => rawData += chunk); res.on('end', () => { try { - let parsedData = JSON.parse(rawData); + const parsedData = JSON.parse(rawData); console.log(parsedData); } catch (e) { console.log(e.message); @@ -1584,11 +1587,11 @@ upload a file with a POST request, then write to the `ClientRequest` object. Example: ```js -var postData = querystring.stringify({ - 'msg' : 'Hello World!' +const postData = querystring.stringify({ + 'msg': 'Hello World!' }); -var options = { +const options = { hostname: 'www.google.com', port: 80, path: '/upload', @@ -1599,7 +1602,7 @@ var options = { } }; -var req = http.request(options, (res) => { +const req = http.request(options, (res) => { console.log(`STATUS: ${res.statusCode}`); console.log(`HEADERS: ${JSON.stringify(res.headers)}`); res.setEncoding('utf8'); diff --git a/doc/api/modules.md b/doc/api/modules.md index a2d2beb753ebfd..480f9e10ea57be 100644 --- a/doc/api/modules.md +++ b/doc/api/modules.md @@ -67,11 +67,7 @@ The module system is implemented in the `require('module')` module. When a file is run directly from Node.js, `require.main` is set to its `module`. That means that you can determine whether a file has been run -directly by testing - -```js -require.main === module -``` +directly by testing `require.main === module`. For a file `foo.js`, this will be `true` if run via `node foo.js`, but `false` if run by `require('./foo')`. @@ -441,7 +437,7 @@ Before a module's code is executed, Node.js will wrap it with a function wrapper that looks like the following: ```js -(function (exports, require, module, __filename, __dirname) { +(function(exports, require, module, __filename, __dirname) { // Your module code actually lives in here }); ``` @@ -556,6 +552,7 @@ exports = { hello: false }; // Not exported, only available in the module When the `module.exports` property is being completely replaced by a new object, it is common to also reassign `exports`, for example: + ```js module.exports = exports = function Constructor() { // ... etc. diff --git a/doc/api/net.md b/doc/api/net.md index e11f6cd627204e..18ba6a6fabae48 100644 --- a/doc/api/net.md +++ b/doc/api/net.md @@ -325,6 +325,7 @@ Construct a new socket object. `options` is an object with the following defaults: + ```js { fd: null, @@ -837,6 +838,7 @@ automatically set as a listener for the [`'connection'`][] event. `options` is an object with the following defaults: + ```js { allowHalfOpen: false, diff --git a/doc/api/os.md b/doc/api/os.md index 4009e53bcd5eac..84cb2ba3ff6b7c 100644 --- a/doc/api/os.md +++ b/doc/api/os.md @@ -71,6 +71,7 @@ The properties included on each object include: For example: + ```js [ { @@ -253,6 +254,7 @@ The properties available on the assigned network address object include: * `scopeid` {number} The numeric IPv6 scope ID (only specified when `family` is `IPv6`) + ```js { lo: [ diff --git a/doc/api/path.md b/doc/api/path.md index 5ccd5e021e5563..27ca6be6fed7ac 100644 --- a/doc/api/path.md +++ b/doc/api/path.md @@ -70,10 +70,10 @@ the Unix `basename` command. Trailing directory separators are ignored, see For example: ```js -path.basename('/foo/bar/baz/asdf/quux.html') +path.basename('/foo/bar/baz/asdf/quux.html'); // Returns: 'quux.html' -path.basename('/foo/bar/baz/asdf/quux.html', '.html') +path.basename('/foo/bar/baz/asdf/quux.html', '.html'); // Returns: 'quux' ``` @@ -95,21 +95,21 @@ Provides the platform-specific path delimiter: For example, on POSIX: ```js -console.log(process.env.PATH) +console.log(process.env.PATH); // Prints: '/usr/bin:/bin:/usr/sbin:/sbin:/usr/local/bin' -process.env.PATH.split(path.delimiter) +process.env.PATH.split(path.delimiter); // Returns: ['/usr/bin', '/bin', '/usr/sbin', '/sbin', '/usr/local/bin'] ``` On Windows: ```js -console.log(process.env.PATH) +console.log(process.env.PATH); // Prints: 'C:\Windows\system32;C:\Windows;C:\Program Files\node\' -process.env.PATH.split(path.delimiter) -// Returns: ['C:\\Windows\\system32', 'C:\\Windows', 'C:\\Program Files\\node\\'] +process.env.PATH.split(path.delimiter); +// Returns ['C:\\Windows\\system32', 'C:\\Windows', 'C:\\Program Files\\node\\'] ``` ## path.dirname(path) @@ -127,7 +127,7 @@ the Unix `dirname` command. Trailing directory separators are ignored, see For example: ```js -path.dirname('/foo/bar/baz/asdf/quux') +path.dirname('/foo/bar/baz/asdf/quux'); // Returns: '/foo/bar/baz/asdf' ``` @@ -150,19 +150,19 @@ an empty string is returned. For example: ```js -path.extname('index.html') +path.extname('index.html'); // Returns: '.html' -path.extname('index.coffee.md') +path.extname('index.coffee.md'); // Returns: '.md' -path.extname('index.') +path.extname('index.'); // Returns: '.' -path.extname('index') +path.extname('index'); // Returns: '' -path.extname('.index') +path.extname('.index'); // Returns: '' ``` @@ -226,8 +226,8 @@ On Windows: ```js path.format({ - dir : "C:\\path\\dir", - base : "file.txt" + dir: 'C:\\path\\dir', + base: 'file.txt' }); // Returns: 'C:\\path\\dir\\file.txt' ``` @@ -247,22 +247,22 @@ If the given `path` is a zero-length string, `false` will be returned. For example on POSIX: ```js -path.isAbsolute('/foo/bar') // true -path.isAbsolute('/baz/..') // true -path.isAbsolute('qux/') // false -path.isAbsolute('.') // false +path.isAbsolute('/foo/bar'); // true +path.isAbsolute('/baz/..'); // true +path.isAbsolute('qux/'); // false +path.isAbsolute('.'); // false ``` On Windows: ```js -path.isAbsolute('//server') // true -path.isAbsolute('\\\\server') // true -path.isAbsolute('C:/foo/..') // true -path.isAbsolute('C:\\foo\\..') // true -path.isAbsolute('bar\\baz') // false -path.isAbsolute('bar/baz') // false -path.isAbsolute('.') // false +path.isAbsolute('//server'); // true +path.isAbsolute('\\\\server'); // true +path.isAbsolute('C:/foo/..'); // true +path.isAbsolute('C:\\foo\\..'); // true +path.isAbsolute('bar\\baz'); // false +path.isAbsolute('bar/baz'); // false +path.isAbsolute('.'); // false ``` A [`TypeError`][] is thrown if `path` is not a string. @@ -285,11 +285,11 @@ working directory. For example: ```js -path.join('/foo', 'bar', 'baz/asdf', 'quux', '..') +path.join('/foo', 'bar', 'baz/asdf', 'quux', '..'); // Returns: '/foo/bar/baz/asdf' -path.join('foo', {}, 'bar') -// throws TypeError: Arguments to path.join must be strings +path.join('foo', {}, 'bar'); +// throws 'TypeError: Path must be a string. Received {}' ``` A [`TypeError`][] is thrown if any of the path segments is not a string. @@ -316,7 +316,7 @@ current working directory. For example on POSIX: ```js -path.normalize('/foo/bar//baz/asdf/quux/..') +path.normalize('/foo/bar//baz/asdf/quux/..'); // Returns: '/foo/bar/baz/asdf' ``` @@ -360,7 +360,7 @@ The returned object will have the following properties: For example on POSIX: ```js -path.parse('/home/user/dir/file.txt') +path.parse('/home/user/dir/file.txt'); // Returns: // { // root : "/", @@ -384,7 +384,7 @@ path.parse('/home/user/dir/file.txt') On Windows: ```js -path.parse('C:\\path\\dir\\file.txt') +path.parse('C:\\path\\dir\\file.txt'); // Returns: // { // root : "C:\\", @@ -436,14 +436,14 @@ directory will be used instead of the zero-length strings. For example on POSIX: ```js -path.relative('/data/orandea/test/aaa', '/data/orandea/impl/bbb') +path.relative('/data/orandea/test/aaa', '/data/orandea/impl/bbb'); // Returns: '../../impl/bbb' ``` On Windows: ```js -path.relative('C:\\orandea\\test\\aaa', 'C:\\orandea\\impl\\bbb') +path.relative('C:\\orandea\\test\\aaa', 'C:\\orandea\\impl\\bbb'); // Returns: '..\\..\\impl\\bbb' ``` @@ -479,13 +479,13 @@ of the current working directory. For example: ```js -path.resolve('/foo/bar', './baz') +path.resolve('/foo/bar', './baz'); // Returns: '/foo/bar/baz' -path.resolve('/foo/bar', '/tmp/file/') +path.resolve('/foo/bar', '/tmp/file/'); // Returns: '/tmp/file' -path.resolve('wwwroot', 'static_files/png/', '../gif/image.gif') +path.resolve('wwwroot', 'static_files/png/', '../gif/image.gif'); // if the current working directory is /home/myself/node, // this returns '/home/myself/node/wwwroot/static_files/gif/image.gif' ``` @@ -507,14 +507,14 @@ Provides the platform-specific path segment separator: For example on POSIX: ```js -'foo/bar/baz'.split(path.sep) +'foo/bar/baz'.split(path.sep); // Returns: ['foo', 'bar', 'baz'] ``` On Windows: ```js -'foo\\bar\\baz'.split(path.sep) +'foo\\bar\\baz'.split(path.sep); // Returns: ['foo', 'bar', 'baz'] ``` diff --git a/doc/api/process.md b/doc/api/process.md index 30438b64cdb9d2..03ccbe9b7aad6e 100644 --- a/doc/api/process.md +++ b/doc/api/process.md @@ -241,7 +241,7 @@ function SomeResource() { this.loaded = Promise.reject(new Error('Resource not yet loaded!')); } -var resource = new SomeResource(); +const resource = new SomeResource(); // no .catch or .then on resource.loaded for at least a turn ``` @@ -530,9 +530,8 @@ console.log(`Starting directory: ${process.cwd()}`); try { process.chdir('/tmp'); console.log(`New directory: ${process.cwd()}`); -} -catch (err) { - console.log(`chdir: ${err}`); +} catch (err) { + console.error(`chdir: ${err}`); } ``` @@ -550,7 +549,8 @@ running the `./configure` script. An example of the possible output looks like: -```txt + +```js { target_defaults: { cflags: [], @@ -670,6 +670,7 @@ See environ(7). An example of this object looks like: + ```js { TERM: 'xterm-256color', @@ -811,7 +812,7 @@ so, it is recommended to place the `emitWarning()` behind a simple boolean flag as illustrated in the example below: ```js -var warned = false; +let warned = false; function emitMyWarning() { if (!warned) { process.emitWarning('Only warn once!'); @@ -846,12 +847,14 @@ $ node --harmony script.js --version Results in `process.execArgv`: + ```js ['--harmony'] ``` And `process.argv`: + ```js ['/usr/local/bin/node', 'script.js', '--version'] ``` @@ -868,6 +871,7 @@ that started the Node.js process. For example: + ```js '/usr/local/bin/node' ``` @@ -1059,11 +1063,11 @@ Passing in the result of a previous call to `process.hrtime()` is useful for calculating an amount of time passed between calls: ```js -var time = process.hrtime(); +const time = process.hrtime(); // [ 1800216, 25 ] setTimeout(() => { - var diff = process.hrtime(time); + const diff = process.hrtime(time); // [ 1, 552 ] console.log(`Benchmark took ${diff[0] * 1e9 + diff[1]} nanoseconds`); @@ -1179,6 +1183,7 @@ console.log(process.memoryUsage()); Will generate: + ```js { rss: 4935680, @@ -1233,7 +1238,7 @@ function MyThing(options) { }); } -var thing = new MyThing(); +const thing = new MyThing(); thing.getReadyForStuff(); // thing.startDoingStuff() gets called now, not before. @@ -1348,6 +1353,7 @@ tarball. For example: + ```js { name: 'node', @@ -1401,8 +1407,7 @@ if (process.getegid && process.setegid) { try { process.setegid(501); console.log(`New gid: ${process.getegid()}`); - } - catch (err) { + } catch (err) { console.log(`Failed to set gid: ${err}`); } } @@ -1430,8 +1435,7 @@ if (process.geteuid && process.seteuid) { try { process.seteuid(501); console.log(`New uid: ${process.geteuid()}`); - } - catch (err) { + } catch (err) { console.log(`Failed to set uid: ${err}`); } } @@ -1458,8 +1462,7 @@ if (process.getgid && process.setgid) { try { process.setgid(501); console.log(`New gid: ${process.getgid()}`); - } - catch (err) { + } catch (err) { console.log(`Failed to set gid: ${err}`); } } @@ -1500,8 +1503,7 @@ if (process.getuid && process.setuid) { try { process.setuid(501); console.log(`New uid: ${process.getuid()}`); - } - catch (err) { + } catch (err) { console.log(`Failed to set uid: ${err}`); } } @@ -1538,7 +1540,7 @@ For example: process.stdin.setEncoding('utf8'); process.stdin.on('readable', () => { - var chunk = process.stdin.read(); + const chunk = process.stdin.read(); if (chunk !== null) { process.stdout.write(`data: ${chunk}`); } @@ -1709,6 +1711,7 @@ console.log(process.versions); Will generate an object similar to: + ```js { http_parser: '2.3.0', diff --git a/doc/api/querystring.md b/doc/api/querystring.md index a1ee5e62b87700..3a10604020db90 100644 --- a/doc/api/querystring.md +++ b/doc/api/querystring.md @@ -49,6 +49,7 @@ collection of key and value pairs. For example, the query string `'foo=bar&abc=xyz&abc=123'` is parsed into: + ```js { foo: 'bar', @@ -70,7 +71,7 @@ in the following example: // Assuming gbkDecodeURIComponent function already exists... querystring.parse('w=%D6%D0%CE%C4&foo=bar', null, null, - { decodeURIComponent: gbkDecodeURIComponent }) + { decodeURIComponent: gbkDecodeURIComponent }); ``` ## querystring.stringify(obj[, sep[, eq[, options]]]) @@ -98,10 +99,10 @@ Any other input values will be coerced to empty strings. For example: ```js -querystring.stringify({ foo: 'bar', baz: ['qux', 'quux'], corge: '' }) +querystring.stringify({ foo: 'bar', baz: ['qux', 'quux'], corge: '' }); // returns 'foo=bar&baz=qux&baz=quux&corge=' -querystring.stringify({ foo: 'bar', baz: 'qux' }, ';', ':') +querystring.stringify({ foo: 'bar', baz: 'qux' }, ';', ':'); // returns 'foo:bar;baz:qux' ``` @@ -114,7 +115,7 @@ following example: // Assuming gbkEncodeURIComponent function already exists, querystring.stringify({ w: '中文', foo: 'bar' }, null, null, - { encodeURIComponent: gbkEncodeURIComponent }) + { encodeURIComponent: gbkEncodeURIComponent }); ``` ## querystring.unescape(str) diff --git a/doc/api/readline.md b/doc/api/readline.md index 6fdee2c0449de5..fab1e9b3ed80f3 100644 --- a/doc/api/readline.md +++ b/doc/api/readline.md @@ -485,7 +485,7 @@ const rl = readline.createInterface({ rl.prompt(); rl.on('line', (line) => { - switch(line.trim()) { + switch (line.trim()) { case 'hello': console.log('world!'); break; diff --git a/doc/api/repl.md b/doc/api/repl.md index 248d87991bb8ff..ed1425350d19f1 100644 --- a/doc/api/repl.md +++ b/doc/api/repl.md @@ -40,6 +40,7 @@ The following special commands are supported by all REPL instances: `> .load ./file/to/load.js` * `.editor` - Enter editor mode (`-D` to finish, `-C` to cancel) + ```js > .editor // Entering editor mode (^D to finish, ^C to cancel) @@ -75,6 +76,7 @@ evaluation function when the `repl.REPLServer` instance is created. The default evaluator supports direct evaluation of JavaScript expressions: + ```js > 1 + 1 2 @@ -96,13 +98,14 @@ it to the `context` object associated with each `REPLServer`. For example: ```js const repl = require('repl'); -var msg = 'message'; +const msg = 'message'; repl.start('> ').context.m = msg; ``` Properties in the `context` object appear as local within the REPL: + ```js $ node repl_test.js > m @@ -115,7 +118,7 @@ To specify read-only globals, context properties must be defined using ```js const repl = require('repl'); -var msg = 'message'; +const msg = 'message'; const r = repl.start('> '); Object.defineProperty(r.context, 'm', { @@ -132,6 +135,7 @@ REPL environment when used. For instance, unless otherwise declared as a global or scoped variable, the input `fs` will be evaluated on-demand as `global.fs = require('fs')`. + ```js > fs.createReadStream('./some/file'); ``` @@ -141,6 +145,7 @@ global or scoped variable, the input `fs` will be evaluated on-demand as The default evaluator will, by default, assign the result of the most recently evaluated expression to the special variable `_` (underscore). + ```js > [ 'a', 'b', 'c' ] [ 'a', 'b', 'c' ] @@ -183,7 +188,7 @@ to the provided callback function: ```js function eval(cmd, context, filename, callback) { - var result; + let result; try { result = vm.runInThisContext(cmd); } catch (e) { @@ -220,7 +225,7 @@ const repl = require('repl'); const r = repl.start({prompt: '>', eval: myEval, writer: myWriter}); function myEval(cmd, context, filename, callback) { - callback(null,cmd); + callback(null, cmd); } function myWriter(output) { @@ -275,7 +280,7 @@ function initializeContext(context) { context.m = 'test'; } -var r = repl.start({prompt: '>'}); +const r = repl.start({prompt: '>'}); initializeContext(r.context); r.on('reset', initializeContext); @@ -284,6 +289,7 @@ r.on('reset', initializeContext); When this code is executed, the global `'m'` variable can be modified but then reset to its initial value using the `.clear` command: + ```js $ ./node example.js >m @@ -321,7 +327,7 @@ The following example shows two new commands added to the REPL instance: ```js const repl = require('repl'); -var replServer = repl.start({prompt: '> '}); +const replServer = repl.start({prompt: '> '}); replServer.defineCommand('sayhello', { help: 'Say hello', action: function(name) { @@ -428,6 +434,7 @@ Node.js itself uses the `repl` module to provide its own interactive interface for executing JavaScript. This can be used by executing the Node.js binary without passing any arguments (or by passing the `-i` argument): + ```js $ node > a = [1, 2, 3]; @@ -502,7 +509,7 @@ socket, and a TCP socket: ```js const net = require('net'); const repl = require('repl'); -var connections = 0; +let connections = 0; repl.start({ prompt: 'Node.js via stdin> ', diff --git a/doc/api/stream.md b/doc/api/stream.md index e3fb35deba54c3..69efa51158ff9e 100644 --- a/doc/api/stream.md +++ b/doc/api/stream.md @@ -112,7 +112,7 @@ that implements an HTTP server: ```js const http = require('http'); -const server = http.createServer( (req, res) => { +const server = http.createServer((req, res) => { // req is an http.IncomingMessage, which is a Readable Stream // res is an http.ServerResponse, which is a Writable Stream @@ -237,7 +237,7 @@ function writeOneMillionTimes(writer, data, encoding, callback) { let i = 1000000; write(); function write() { - var ok = true; + let ok = true; do { i--; if (i === 0) { @@ -280,7 +280,7 @@ has been called, and all data has been flushed to the underlying system. ```js const writer = getWritableStreamSomehow(); -for (var i = 0; i < 100; i ++) { +for (let i = 0; i < 100; i++) { writer.write(`hello, #${i}!\n`); } writer.end('This is the end\n'); @@ -474,18 +474,18 @@ possible to respect backpressure and avoid memory issues using the [`'drain'`][] event: ```js -function write (data, cb) { +function write(data, cb) { if (!stream.write(data)) { - stream.once('drain', cb) + stream.once('drain', cb); } else { - process.nextTick(cb) + process.nextTick(cb); } } // Wait for cb to be called before doing any other write. write('hello', () => { - console.log('write completed, do more writes now') -}) + console.log('write completed, do more writes now'); +}); ``` A Writable stream in object mode will always ignore the `encoding` argument. @@ -755,13 +755,13 @@ Readable. This is used primarily by the mechanism that underlies the use this method directly. ```js -const readable = new stream.Readable +const readable = new stream.Readable(); -readable.isPaused() // === false -readable.pause() -readable.isPaused() // === true -readable.resume() -readable.isPaused() // === false +readable.isPaused(); // === false +readable.pause(); +readable.isPaused(); // === true +readable.resume(); +readable.isPaused(); // === false ``` ##### readable.pause() @@ -875,7 +875,7 @@ the internal buffer is fully drained. ```js const readable = getReadableStreamSomehow(); readable.on('readable', () => { - var chunk; + let chunk; while (null !== (chunk = readable.read())) { console.log(`Received ${chunk.length} bytes of data.`); } @@ -1007,14 +1007,14 @@ function parseHeader(stream, callback) { stream.on('error', callback); stream.on('readable', onReadable); const decoder = new StringDecoder('utf8'); - var header = ''; + let header = ''; function onReadable() { - var chunk; + let chunk; while (null !== (chunk = stream.read())) { - var str = decoder.write(chunk); + const str = decoder.write(chunk); if (str.match(/\n\n/)) { // found the header boundary - var split = str.split(/\n\n/); + const split = str.split(/\n\n/); header += split.shift(); const remaining = split.join('\n\n'); const buf = Buffer.from(remaining, 'utf8'); @@ -1068,7 +1068,7 @@ For example: ```js const OldReader = require('./old-api-module.js').OldReader; const Readable = require('stream').Readable; -const oreader = new OldReader; +const oreader = new OldReader(); const myReader = new Readable().wrap(oreader); myReader.on('readable', () => { @@ -1597,12 +1597,12 @@ class Counter extends Readable { } _read() { - var i = this._index++; + const i = this._index++; if (i > this._max) this.push(null); else { - var str = '' + i; - var buf = Buffer.from(str, 'ascii'); + const str = '' + i; + const buf = Buffer.from(str, 'ascii'); this.push(buf); } } @@ -1906,12 +1906,12 @@ argument is passed to the `callback`, it will be forwarded on to the `readable.push()` method. In other words the following are equivalent: ```js -transform.prototype._transform = function (data, encoding, callback) { +transform.prototype._transform = function(data, encoding, callback) { this.push(data); callback(); }; -transform.prototype._transform = function (data, encoding, callback) { +transform.prototype._transform = function(data, encoding, callback) { callback(null, data); }; ``` diff --git a/doc/api/url.md b/doc/api/url.md index 625247f0a24f4a..1cb3e2f89f0fd8 100644 --- a/doc/api/url.md +++ b/doc/api/url.md @@ -232,9 +232,9 @@ manner similar to that of a Web browser resolving an anchor tag HREF. For example: ```js -url.resolve('/one/two/three', 'four') // '/one/two/four' -url.resolve('http://example.com/', '/one') // 'http://example.com/one' -url.resolve('http://example.com/one', '/two') // 'http://example.com/two' +url.resolve('/one/two/three', 'four'); // '/one/two/four' +url.resolve('http://example.com/', '/one'); // 'http://example.com/one' +url.resolve('http://example.com/one', '/two'); // 'http://example.com/two' ``` ## Escaped Characters diff --git a/doc/api/util.md b/doc/api/util.md index b97b6f133378cb..ec5ec635d16fdf 100644 --- a/doc/api/util.md +++ b/doc/api/util.md @@ -59,7 +59,7 @@ it is marked as deprecated. const util = require('util'); exports.puts = util.deprecate(function() { - for (var i = 0, len = arguments.length; i < len; ++i) { + for (let i = 0, len = arguments.length; i < len; ++i) { process.stdout.write(arguments[i] + '\n'); } }, 'util.puts: Use console.log instead'); @@ -308,7 +308,8 @@ class Box { // Five space padding because that's the size of "Box< ". const padding = ' '.repeat(5); - const inner = util.inspect(this.value, newOptions).replace(/\n/g, '\n' + padding); + const inner = util.inspect(this.value, newOptions) + .replace(/\n/g, '\n' + padding); return options.stylize('Box', 'special') + '< ' + inner + ' >'; } } @@ -426,7 +427,7 @@ const util = require('util'); util.isArray([]); // Returns: true -util.isArray(new Array); +util.isArray(new Array()); // Returns: true util.isArray({}); // Returns: false @@ -662,7 +663,7 @@ util.isObject(null); // Returns: false util.isObject({}); // Returns: true -util.isObject(function(){}); +util.isObject(function() {}); // Returns: false ``` diff --git a/doc/api/v8.md b/doc/api/v8.md index 82169d04869dea..904bfddf5d2e92 100644 --- a/doc/api/v8.md +++ b/doc/api/v8.md @@ -25,6 +25,7 @@ Returns an object with the following properties: For example: + ```js { total_heap_size: 7326976, diff --git a/doc/api/vm.md b/doc/api/vm.md index f1596c617a6ac2..7d04cbd4d1689d 100644 --- a/doc/api/vm.md +++ b/doc/api/vm.md @@ -107,7 +107,7 @@ const sandbox = { const script = new vm.Script('count += 1; name = "kitty";'); const context = new vm.createContext(sandbox); -for (var i = 0; i < 10; ++i) { +for (let i = 0; i < 10; ++i) { script.runInContext(context); } @@ -198,7 +198,7 @@ global.globalVar = 0; const script = new vm.Script('globalVar += 1', { filename: 'myfile.vm' }); -for (var i = 0; i < 1000; ++i) { +for (let i = 0; i < 1000; ++i) { script.runInThisContext(); } @@ -226,14 +226,14 @@ will remain unchanged. const util = require('util'); const vm = require('vm'); -var globalVar = 3; +global.globalVar = 3; const sandbox = { globalVar: 1 }; vm.createContext(sandbox); vm.runInContext('globalVar *= 2;', sandbox); -console.log(util.inspect(sandbox)); // 2 +console.log(util.inspect(sandbox)); // { globalVar: 2 } console.log(util.inspect(globalVar)); // 3 ``` @@ -291,7 +291,7 @@ const vm = require('vm'); const sandbox = { globalVar: 1 }; vm.createContext(sandbox); -for (var i = 0; i < 10; ++i) { +for (let i = 0; i < 10; ++i) { vm.runInContext('globalVar *= 2;', sandbox); } console.log(util.inspect(sandbox)); @@ -394,9 +394,10 @@ local scope, but does have access to the current `global` object. The following example illustrates using both `vm.runInThisContext()` and the JavaScript [`eval()`][] function to run the same code: + ```js const vm = require('vm'); -var localVar = 'initial value'; +let localVar = 'initial value'; const vmResult = vm.runInThisContext('localVar = "vm";'); console.log('vmResult:', vmResult); @@ -430,7 +431,7 @@ to the `http` module passed to it. For instance: 'use strict'; const vm = require('vm'); -let code = +const code = `(function(require) { const http = require('http'); @@ -443,7 +444,7 @@ let code = console.log('Server running at http://127.0.0.1:8124/'); })`; - vm.runInThisContext(code)(require); +vm.runInThisContext(code)(require); ``` *Note*: The `require()` in the above case shares the state with the context it diff --git a/doc/api/zlib.md b/doc/api/zlib.md index a08cf9a4afc1e6..17a1464b159de3 100644 --- a/doc/api/zlib.md +++ b/doc/api/zlib.md @@ -65,11 +65,11 @@ const zlib = require('zlib'); const http = require('http'); const fs = require('fs'); const request = http.get({ host: 'example.com', - path: '/', - port: 80, - headers: { 'Accept-Encoding': 'gzip,deflate' } }); + path: '/', + port: 80, + headers: { 'Accept-Encoding': 'gzip,deflate' } }); request.on('response', (response) => { - var output = fs.createWriteStream('example.com_index.html'); + const output = fs.createWriteStream('example.com_index.html'); switch (response.headers['content-encoding']) { // or, just use zlib.createUnzip() to handle both cases @@ -94,8 +94,8 @@ const zlib = require('zlib'); const http = require('http'); const fs = require('fs'); http.createServer((request, response) => { - var raw = fs.createReadStream('index.html'); - var acceptEncoding = request.headers['accept-encoding']; + const raw = fs.createReadStream('index.html'); + let acceptEncoding = request.headers['accept-encoding']; if (!acceptEncoding) { acceptEncoding = ''; } @@ -125,13 +125,16 @@ method that is used to compressed the last chunk of input data: // This is a truncated version of the buffer from the above examples const buffer = Buffer.from('eJzT0yMA', 'base64'); -zlib.unzip(buffer, { finishFlush: zlib.Z_SYNC_FLUSH }, (err, buffer) => { - if (!err) { - console.log(buffer.toString()); - } else { - // handle error - } -}); +zlib.unzip( + buffer, + { finishFlush: zlib.Z_SYNC_FLUSH }, + (err, buffer) => { + if (!err) { + console.log(buffer.toString()); + } else { + // handle error + } + }); ``` This will not change the behavior in other error-throwing situations, e.g. @@ -149,7 +152,7 @@ From `zlib/zconf.h`, modified to node.js's usage: The memory requirements for deflate are (in bytes): ```js -(1 << (windowBits+2)) + (1 << (memLevel+9)) +(1 << (windowBits + 2)) + (1 << (memLevel + 9)); ``` That is: 128K for windowBits=15 + 128K for memLevel = 8 @@ -167,7 +170,7 @@ This will, however, generally degrade compression. The memory requirements for inflate are (in bytes) ```js -1 << windowBits +1 << windowBits; ``` That is, 32K for windowBits=15 (default value) plus a few kilobytes diff --git a/doc/guides/timers-in-node.md b/doc/guides/timers-in-node.md index 818cc793437cad..4c66312c0076a5 100644 --- a/doc/guides/timers-in-node.md +++ b/doc/guides/timers-in-node.md @@ -35,7 +35,7 @@ arguments may also be included and these will be passed on to the function. Here is an example of that: ```js -function myFunc (arg) { +function myFunc(arg) { console.log('arg was => ' + arg); } @@ -111,7 +111,7 @@ that may hold on to the event loop, and therefore should be treated as an approximate delay. See the below example: ```js -function intervalFunc () { +function intervalFunc() { console.log('Cant stop me now!'); } @@ -134,15 +134,15 @@ that object will be halted completely. The respective functions are below for an example of each: ```js -let timeoutObj = setTimeout(() => { +const timeoutObj = setTimeout(() => { console.log('timeout beyond time'); }, 1500); -let immediateObj = setImmediate(() => { +const immediateObj = setImmediate(() => { console.log('immediately executing immediate'); }); -let intervalObj = setInterval(() => { +const intervalObj = setInterval(() => { console.log('interviewing the interval'); }, 500); @@ -168,9 +168,9 @@ not *exactly* restore the initial behavior for performance reasons. See below for examples of both: ```js -let timerObj = setTimeout(() => { +const timerObj = setTimeout(() => { console.log('will i run?'); -}); +}, 1); // if left alone, this statement will keep the above // timeout from running, since the timeout will be the only diff --git a/doc/guides/writing-tests.md b/doc/guides/writing-tests.md index 0f5ff304930e0a..fbb1d55309a44b 100644 --- a/doc/guides/writing-tests.md +++ b/doc/guides/writing-tests.md @@ -141,22 +141,22 @@ this with a real test from the test suite. ```javascript 'use strict'; -var common = require('../common'); -var assert = require('assert'); -var http = require('http'); +require('../common'); +const assert = require('assert'); +const http = require('http'); -var request = 0; -var response = 0; +let request = 0; +let response = 0; process.on('exit', function() { assert.equal(request, 1, 'http server "request" callback was not called'); assert.equal(response, 1, 'http request "response" callback was not called'); }); -var server = http.createServer(function(req, res) { +const server = http.createServer(function(req, res) { request++; res.end(); }).listen(0, function() { - var options = { + const options = { agent: null, port: this.address().port }; @@ -172,14 +172,13 @@ This test could be greatly simplified by using `common.mustCall` like this: ```javascript 'use strict'; -var common = require('../common'); -var assert = require('assert'); -var http = require('http'); +const common = require('../common'); +const http = require('http'); -var server = http.createServer(common.mustCall(function(req, res) { +const server = http.createServer(common.mustCall(function(req, res) { res.end(); })).listen(0, function() { - var options = { + const options = { agent: null, port: this.address().port }; diff --git a/doc/topics/domain-postmortem.md b/doc/topics/domain-postmortem.md index e03012db926b08..c1f8f7e6352c5c 100644 --- a/doc/topics/domain-postmortem.md +++ b/doc/topics/domain-postmortem.md @@ -127,11 +127,11 @@ d1.run(() => setTimeout(() => { setTimeout(() => { setTimeout(() => { throw new Error('outer'); - }); - throw new Error('inner') - }); + }, 1); + throw new Error('inner'); + }, 1); }); -})); +}, 1)); ``` Even in the case that the domain instances are being used for local storage so @@ -216,7 +216,7 @@ const server = net.createServer((c) => { // for demonstration purposes. const ds = new DataStream(dataTransformed); c.on('data', (chunk) => ds.data(chunk)); -}).listen(8080, () => console.log(`listening on 8080`)); +}).listen(8080, () => console.log('listening on 8080')); function dataTransformed(chunk) { // FAIL! Because the DataStream instance also created a @@ -241,12 +241,12 @@ DataStream.prototype.data = function data(chunk) { this.domain.run(function() { // Simulate an async operation that does the data transform. setImmediate(() => { - for (var i = 0; i < chunk.length; i++) + for (let i = 0; i < chunk.length; i++) chunk[i] = ((chunk[i] + Math.random() * 100) % 96) + 33; // Grab the instance from the active domain and use that // to call the user's callback. const self = domain.active.data.inst; - self.cb.call(self, chunk); + self.cb(chunk); }); }); }; diff --git a/doc/topics/event-loop-timers-and-nexttick.md b/doc/topics/event-loop-timers-and-nexttick.md index d7d0ee96e9c438..377b14c9babc36 100644 --- a/doc/topics/event-loop-timers-and-nexttick.md +++ b/doc/topics/event-loop-timers-and-nexttick.md @@ -101,32 +101,31 @@ threshold, then your script starts asynchronously reading a file which takes 95 ms: ```js +const fs = require('fs'); -var fs = require('fs'); - -function someAsyncOperation (callback) { +function someAsyncOperation(callback) { // Assume this takes 95ms to complete fs.readFile('/path/to/file', callback); } -var timeoutScheduled = Date.now(); +const timeoutScheduled = Date.now(); -setTimeout(function () { +setTimeout(function() { - var delay = Date.now() - timeoutScheduled; + const delay = Date.now() - timeoutScheduled; - console.log(delay + "ms have passed since I was scheduled"); + console.log(delay + 'ms have passed since I was scheduled'); }, 100); // do someAsyncOperation which takes 95 ms to complete -someAsyncOperation(function () { +someAsyncOperation(function() { - var startCallback = Date.now(); + const startCallback = Date.now(); // do something that will take 10ms... while (Date.now() - startCallback < 10) { - ; // do nothing + // do nothing } }); @@ -233,11 +232,11 @@ process: ```js // timeout_vs_immediate.js -setTimeout(function timeout () { +setTimeout(function timeout() { console.log('timeout'); -},0); +}, 0); -setImmediate(function immediate () { +setImmediate(function immediate() { console.log('immediate'); }); ``` @@ -257,16 +256,16 @@ callback is always executed first: ```js // timeout_vs_immediate.js -var fs = require('fs') +const fs = require('fs'); fs.readFile(__filename, () => { setTimeout(() => { - console.log('timeout') - }, 0) + console.log('timeout'); + }, 0); setImmediate(() => { - console.log('immediate') - }) -}) + console.log('immediate'); + }); +}); ``` ```console @@ -307,10 +306,10 @@ design philosophy where an API should always be asynchronous even where it doesn't have to be. Take this code snippet for example: ```js -function apiCall (arg, callback) { +function apiCall(arg, callback) { if (typeof arg !== 'string') return process.nextTick(callback, - new TypeError('argument should be string')); + new TypeError('argument should be string')); } ``` @@ -333,8 +332,10 @@ This philosophy can lead to some potentially problematic situations. Take this snippet for example: ```js +let bar; + // this has an asynchronous signature, but calls callback synchronously -function someAsyncApiCall (callback) { callback(); }; +function someAsyncApiCall(callback) { callback(); } // the callback is called before `someAsyncApiCall` completes. someAsyncApiCall(() => { @@ -344,7 +345,7 @@ someAsyncApiCall(() => { }); -var bar = 1; +bar = 1; ``` The user defines `someAsyncApiCall()` to have an asynchronous signature, @@ -363,15 +364,17 @@ useful for the user to be alerted to an error before the event loop is allowed to continue. Here is the previous example using `process.nextTick()`: ```js -function someAsyncApiCall (callback) { +let bar; + +function someAsyncApiCall(callback) { process.nextTick(callback); -}; +} someAsyncApiCall(() => { console.log('bar', bar); // 1 }); -var bar = 1; +bar = 1; ``` Here's another real world example: @@ -423,7 +426,7 @@ stack has unwound but before the event loop continues. One example is to match the user's expectations. Simple example: ```js -var server = net.createServer(); +const server = net.createServer(); server.on('connection', function(conn) { }); server.listen(8080); @@ -471,7 +474,7 @@ function MyEmitter() { EventEmitter.call(this); // use nextTick to emit the event once a handler is assigned - process.nextTick(function () { + process.nextTick(function() { this.emit('event'); }.bind(this)); } diff --git a/tools/icu/README.md b/tools/icu/README.md index ed540c672599ed..7f689305c07ad1 100644 --- a/tools/icu/README.md +++ b/tools/icu/README.md @@ -25,8 +25,10 @@ make test-ci ``` Also running + + ```js - new Intl.DateTimeFormat('es',{month:'long'}).format(new Date(9E8)); +new Intl.DateTimeFormat('es', { month: 'long' }).format(new Date(9E8)); ``` …Should return `January` not `enero`. @@ -49,9 +51,11 @@ make ``` - Test this newly default-generated Node.js + + ```js process.versions.icu; -new Intl.DateTimeFormat('es',{month:'long'}).format(new Date(9E8)); +new Intl.DateTimeFormat('es', { month: 'long' }).format(new Date(9E8)); ``` (should return your updated ICU version number, and also `January` again.)