Skip to content

Node Fetch

Node Fetch is a light-weight module that brings the Fetch API to Node.js.

Full documentation: https://www.npmjs.com/package/node-fetch

There are currently two implementations of Node Fetch in Djot - #djot/nodeFetch which is a simple request wrapper which can extract text/json and #djot/nodeFetch2 which accepts an onMessage callback for streaming data (for example with OpenAI API to stream responses).

Beta Note

The current imeplementation and documentation is in beta and is subject to change.

The current implementation is a patch solution to allow the use of the built-in module in Djot - it is not the final solution.

Usage

tsx
import nodeFetch from "#djot/nodeFetch";

export const App = () => {
  const [output, setOutput] = React.useState("");

  const handleClick = async () => {
    const response = await nodeFetch(
      "https://hacker-news.firebaseio.com/v0/item/37621480.json?print=pretty",
      {},
      "json"
    );
    setOutput(response);
  };

  return (
    <>
      <button onClick={handleClick}>Run</button>
      <pre>{JSON.stringify(output, null, 2)}</pre>
    </>
  );
};
import nodeFetch from "#djot/nodeFetch";

export const App = () => {
  const [output, setOutput] = React.useState("");

  const handleClick = async () => {
    const response = await nodeFetch(
      "https://hacker-news.firebaseio.com/v0/item/37621480.json?print=pretty",
      {},
      "json"
    );
    setOutput(response);
  };

  return (
    <>
      <button onClick={handleClick}>Run</button>
      <pre>{JSON.stringify(output, null, 2)}</pre>
    </>
  );
};

Usage with onMessage

tsx
import nodeFetch from "#djot/nodeFetch2";

export const App = () => {
  const [output, setOutput] = React.useState("");

  const handleClick = async () => {
    const url =
      "https://hacker-news.firebaseio.com/v0/item/37621480.json?print=pretty";
    const options = {};
    const onMessage = (data) => {
      if (data)
        setOutput((v) => v + data);
    };
    const response = await nodeFetch(url, options, onMessage);
  };

  return (
    <>
      <button onClick={handleClick}>Run</button>
      <pre>{JSON.stringify(output, null, 2)}</pre>
    </>
  );
};
import nodeFetch from "#djot/nodeFetch2";

export const App = () => {
  const [output, setOutput] = React.useState("");

  const handleClick = async () => {
    const url =
      "https://hacker-news.firebaseio.com/v0/item/37621480.json?print=pretty";
    const options = {};
    const onMessage = (data) => {
      if (data)
        setOutput((v) => v + data);
    };
    const response = await nodeFetch(url, options, onMessage);
  };

  return (
    <>
      <button onClick={handleClick}>Run</button>
      <pre>{JSON.stringify(output, null, 2)}</pre>
    </>
  );
};