random-poll

2.1.0 • Public • Published

random-poll

Import this to run a local server that outputs 4 random numbers in JSON format

Getting Started

Installation

In the terminal type:

  1. npm init -y
  2. npm i random-poll

Quick Start

To start a local server on port 8000 type:

  1. npm start
  2. Then if you go to localhost:8000 you will see an object with 4 random numbers: Image of Yaktocat
  3. Now you can fetch from that url
fetch("http://localhost:8000")
  .then((res) => res.json())
  .then((data) => console.log(data));

Source Code

const http = require("http");
const PORT = 8000;

function getRandom(max) {
  return Math.floor(Math.random() * Math.floor(max));
}

function getNumbers() {
  const MAX = 100;
  const numbers = {
    a: getRandom(MAX),
    b: getRandom(MAX),
    c: getRandom(MAX),
    d: getRandom(MAX),
  };
  return numbers;
}

const requestListener = function (req, res) {
  res.setHeader("Access-Control-Allow-Origin", "*");
  res.writeHead(200);
  res.end(JSON.stringify(getNumbers()));
};

const server = http.createServer(requestListener);
console.log(`listening on port ${PORT}`);
server.listen(PORT);

Versions

Current Tags

  • Version
    Downloads (Last 7 Days)
    • Tag
  • 2.1.0
    0
    • latest

Version History

  • Version
    Downloads (Last 7 Days)
    • Published
  • 2.1.0
    0
  • 2.0.0
    1
  • 1.0.0
    1

Package Sidebar

Install

npm i random-poll

Weekly Downloads

2

Version

2.1.0

License

MIT

Unpacked Size

6.43 kB

Total Files

4

Last publish

Collaborators

  • avcoder