Search

Suggested keywords:
  • Java
  • Docker
  • Git
  • React
  • NextJs
  • Spring boot
  • Laravel

Bun introduces Shell Scripting in to its runtime

  • Share this:

post-title

Bun is considered to be one of fast and better alternative to Node.js. Bun is an all-in-one JavaScript runtime & toolkit designed for speed, complete with a bundler, test runner, and Node.js-compatible package manager.

Recently Bun introduces cross platform shell scripting in to its runtime. Shell is an important tool in developer, Linux administrator, Techie geeks life. Shell helps to interact with the operating system and file system easily. It is a cumbersome task to simulate or recreate the command programatically. To give an example, if we want to list all files in the directory we just need to use ls -l command in the shell. If we have to implement the same functionality in the code then we need to implement as below.

import { readdir } from 'node:fs/promises';

try {
    const files = await readdir("FILE-PATH");
    for (const file of files)
      console.log(file);
  } catch (err) {
    console.error(err);
  } 

Another option is to fork child process using exec() or spawn() from child_process module.

Shell comes with tons of command and it is hard to rewrite programatically and forking child process will give performance issues. To solve the problem, Bun introduces shell embedded in its runtime. Below are few examples of Bun Shell scripting from Bun.

import { $ } from "bun";

// to stdout:
await $`ls *.js`;

// to string:
const text = await $`ls *.js`.text();

 

import { $ } from "bun";

const resp = await fetch("https://www.blackslate.io");

const stdout = await $`gzip -c < ${resp}`.arrayBuffer();

Editorial Team

About author
This article is published by our editorial team.