util

  • [Doc] URL
  • [Doc] Query Strings
  • [Doc] Utilities
  • [Basic] Regex

URL

  1. ┌─────────────────────────────────────────────────────────────────────────────┐
  2. href
  3. ├──────────┬┬───────────┬─────────────────┬───────────────────────────┬───────┤
  4. protocol ││ auth host path hash
  5. ││ ├──────────┬──────┼──────────┬────────────────┤
  6. ││ hostname port pathname search
  7. ││ ├─┬──────────────┤
  8. ││ query
  9. " http: // user:pass @ host.com : 8080 /p/a/t/h ? query=string #hash "
  10. ││
  11. └──────────┴┴───────────┴──────────┴──────┴──────────┴─┴──────────────┴───────┘

Characters escape

A common list of characters that need to be escaped:

Character encodeURI
' ' '%20'
< '%3C'
> '%3E'
" '%22'
` '%60'
\r '%0D'
\n '%0A'
\t '%09'
{ '%7B'
} '%7D'
` ` '%7C'
\\ '%5C'
^ '%5E'
' '%27'

Want to know more? Try this:

  1. Array(range).fill(0)
  2. .map((_, i) => String.fromCharCode(i))
  3. .map(encodeURI)

Try to set the range to 255 first (doge.

Query Strings

A query string is the part of a URL referring to the table above. Node.js provides a module called querystring.

Method Description
.parse(str[, sep[, eq[, options]]]) Parse a query string into a json object
.unescape(str) Inner method used by .parse(). It is exported primarily to allow application code to provide a replacement decoding implementation if necessary
.stringify(obj[, sep[, eq[, options]]])

Converts a json object to a query string|
|.escape(str)|Inner method used by .stringify(). It is exported primarily to allow application code to provide a replacement percent-encoding implementation if necessary.|

So far, the Node.js built-in querystring does not support for the deep structure:

  1. const qs = require('qs'); //
  2. Third party
  3. const querystring = require('querystring'); // Node.js built-in
  4. let obj = { a: { b: { c: 1 } } };
  5. console.log(qs.stringify(obj)); // 'a%5Bb%5D%5Bc%5D=1'
  6. console.log(querystring.stringify(obj)); // 'a='
  7. let str = 'a%5Bb%5D%5Bc%5D=1';
  8. console.log(qs.parse(str)); // { a: { b: { c: '1' } } }
  9. console.log(querystring.parse(str)); // { 'a[b][c]': '1' }

How does HTTP pass let arr = [1,2,3,4] to the server by GET method?

  1. const qs = require('qs');
  2. let arr = [1,2,3,4];
  3. let str = qs.stringify({arr});
  4. console.log(str); // arr%5B0%5D=1&arr%5B1%5D=2&arr%5B2%5D=3&arr%5B3%5D=4
  5. console.log(decodeURI(str)); // 'arr[0]=1&arr[1]=2&arr[2]=3&arr[3]=4'
  6. console.log(qs.parse(str)); // { arr: [ '1', '2', '3', '4' ] }

You can pass arr Array to the server vir https://your.host/api/?arr[0]=1&arr[1]=2&arr[2]=3&arr[3]=4.

util

In v4.0.0 or later, util.is*() is not recommended and deprecated. Maybe it is because that maintaining the library is thankless and there are so many popular libraries. The following is the list:

  • util.debug(string)
  • util.error([…strings])
  • util.isArray(object)
  • util.isBoolean(object)
  • util.isBuffer(object)
  • util.isDate(object)
  • util.isError(object)
  • util.isFunction(object)
  • util.isNull(object)
  • util.isNullOrUndefined(object)
  • util.isNumber(object)
  • util.isObject(object)
  • util.isPrimitive(object)
  • util.isRegExp(object)
  • util.isString(object)
  • util.isSymbol(object)
  • util.isUndefined(object)
  • util.log(string)
  • util.print([…strings])
  • util.puts([…strings])
  • util._extend(target, source)

Most of them can be used as an interview to ask how to implement.

util.inherits

How to implement util.inherits in Node.js?

https://github.com/nodejs/node/blob/v7.6.0/lib/util.js#L960

  1. /**
  2. * Inherit the prototype methods from one constructor into another.
  3. *
  4. * The Function.prototype.inherits from lang.js rewritten as a standalone
  5. * function (not on Function.prototype). NOTE: If this file is to be loaded
  6. * during bootstrapping this function needs to be rewritten using some native
  7. * functions as prototype setup using normal JavaScript does not work as
  8. * expected during bootstrapping (see mirror.js in r114903).
  9. *
  10. * @param {function} ctor Constructor function which needs to inherit the
  11. * prototype.
  12. * @param {function} superCtor Constructor function to inherit prototype from.
  13. * @throws {TypeError} Will error if either constructor is null, or if
  14. * the super constructor lacks a prototype.
  15. */
  16. exports.inherits = function(ctor, superCtor) {
  17. if (ctor === undefined || ctor === null)
  18. throw new TypeError('The constructor to "inherits" must not be ' +
  19. 'null or undefined');
  20. if (superCtor === undefined || superCtor === null)
  21. throw new TypeError('The super constructor to "inherits" must not ' +
  22. 'be null or undefined');
  23. if (superCtor.prototype === undefined)
  24. throw new TypeError('The super constructor to "inherits" must ' +
  25. 'have a prototype');
  26. ctor.super_ = superCtor;
  27. Object.setPrototypeOf(ctor.prototype, superCtor.prototype);
  28. };

Regex

At first, regular expression is a biological expression that used to describe the brain neurons, GNU beard used to do the string match after the original road drifting away. Then it is used by men of GNU to match string, and
deviates from the original road.

Collecting…

Common Modules

Awesome Node.js
Most depended-upon packages

How do I get all the file names under a folder?

  1. const fs = require('fs');
  2. const path = require('path');
  3. function traversal(dir) {
  4. let res = []
  5. for (let item of fs.readdirSync(dir)) {
  6. let filepath = path.join(dir, item);
  7. try {
  8. let fd = fs.openSync(filepath, 'r');
  9. let flag = fs.fstatSync(fd).isDirectory();
  10. fs.close(fd); // TODO
  11. if (flag) {
  12. res.push(...traversal(filepath));
  13. } else {
  14. res.push(filepath);
  15. }
  16. } catch(err) {
  17. if (err.code === 'ENOENT' && // can not open link file
  18. !!fs.readlinkSync(filepath)) { // if it is a link file
  19. res.push(filepath);
  20. } else {
  21. console.error('err', err);
  22. }
  23. }
  24. }
  25. return res.map((file) => path.basename(file));
  26. }
  27. console.log(traversal('.'));

Of course you can also use Oh my glob:

```javascript
const glob = require(“glob”);

glob(“*/.js”, (err, files) {
if (err) {
throw new Error(err);
}
console.log(‘Here you are:’, files.map(path.basename));
});