Doesn't make the API bullet-proof and there are some TODOs left, but greatly improves the situation. Tests were ported from Node.js. Closes https://github.com/denoland/deno/issues/18276.