If you come from Node.js, you might find that a lot of things are very similar in Deno, here we show some features that Deno and Node.js have in common, it would be great for learning purpose.
Keep updating..
- Built-in features
- Check if it's running in Deno
- Command-line arguments
- Spawn a subprocess
- Hashing algorithms
- Colored output
In Node.js, most built-in features are exposed as CommonJS modules which you can use via require
calls, while in Deno, they are exposed on the global namespace Deno
.
For example, in Node.js you use require('child_process').spawn
to start a subprocess, in Deno you can use Deno.run
instead.
For list of all available features go to Deno API Reference.
Due to the fact that Deno exposes its specific features on Deno
namespace, you can use it to determine if your program is running in Deno:
const isDeno = typeof window !== 'undefined' && window.Deno
process.argv
represents command line arguments in Node.js, run the example code:
The first item is the name of the program being executed, in our case, it's an absolute path to node
.
In Deno, you use Deno.args
instead to retrive command line arguments:
Note that there're only three items in the array, the path to deno
executable is not included. To get path to Deno executable use Deno.execPath()
. The first item is also just a relative path.
Node.js's child_process.spawn()
method is used to spawn a new process:
import { spawn } from 'child_process'
const p = spawn('ls', ['./examples'])
p.on('close', code => {
// completed with status `code`
})
p.stdout.on('data', data => {
process.stdout.write(data)
})
p.stderr.on('data', data => {
process.stderr.write(data)
})
Node.js by default creates a pipe between the child process and the parent process for parent-child communication.
The Deno equivalent is Deno.run
:
const p = Deno.run({
args: ['ls', './examples']
})
// await its completion
const code = await p.status()
In Deno the subprocess is inherited from parent process by default, if you want it to work like the default behavior in Node.js you can use piped
option:
const p = Deno.run({
args: ['ls', './examples'],
stdout: 'piped',
stderr: 'piped'
})
const code = await p.status()
if (code === 0) {
const rawOutput = await p.output()
await Deno.stdout.write(rawOutput)
} else {
const rawError = await p.stderrOutput()
await Deno.stderr.write(rawError)
}
In Node.js:
import crypto from 'crypto'
// sha1
console.log(
crypto
.createHash('sha1')
.update('hello world')
.digest('hex')
)
// md5
console.log(
crypto
.createHash('md5')
.update('hello world')
.digest('hex')
)
In Deno:
import { Hash, encode } from 'https://deno.land/x/checksum/mod.ts'
// sha1
console.log(new Hash('sha1').digest(encode('hello world')).hex())
// md5
console.log(new Hash('md5').digest(encode('hello world')).hex())
In Node.js:
import chalk from 'chalk'
console.log(chalk.bold(chalk.bgGreen('foo')))
In Deno:
console.log('%cfoo', 'font-weight:bold;background-color:green')