question-mark
Stuck on an issue?

Lightrun Answers was designed to reduce the constant googling that comes with debugging 3rd party libraries. It collects links to all the places you might be looking at while hunting down a tough bug.

And, if you’re still stuck at the end, we’re happy to hop on a call to see how we can help out.

"Hello World" example

See original GitHub issue

Hi

I tried to work out “hello World” example using the latest techempower code and there are some parts that I am unable to understand.

My code is;

const stringify = require('@stringify')
const http = require('@http')
const process = require('process')

const { createServer, responses } = http
const { sjs, attr } = stringify

const message = 'Hello, World!'
const json = { message }

function spawn (main) {
    if (just.env()['WORKER']) return main()
    const { watch, launch } = process
    const processes = []
    const cpus = parseInt(just.env().CPUS || just.sys.cpus, 10)
    for (let i = 0; i < cpus; i++) {
      just.sys.setenv('WORKER', i)
      //const proc = launch(just.args[0], ['--trace-gc', ...just.args.slice(1)])
      const proc = launch(just.args[0], just.args.slice(1))
      processes.push(proc)
      proc.stats = { user: 0, system: 0 }
    }
    return Promise.all(processes.map(p => watch(p)))
}

class Clock {
    constructor () {
      this.slots = new Map()
    }
  
    unset (callback, repeat = 1000) {
      const current = this.slots.get(repeat)
      if (!current) return
      current.callbacks = current.callbacks.filter(cb => cb !== callback)
      if (!current.callbacks.length) {
        just.clearTimeout(current.timer)
        this.slots.delete(repeat)
      }
    }
  
    set (callback, repeat = 1000) {
      let current = this.slots.get(repeat)
      if (current) {
        current.callbacks.push(callback)
        return
      }
      current = {
        callbacks: [callback],
        timer: just.setInterval(() => current.callbacks.forEach(cb => cb()), repeat)
      }
      this.slots.set(repeat, current)
    }
}

async function main() {
    const sJSON = sjs({ message: attr('string') })

    const server = createServer()
        .get('/plaintext', res => res.text(message))
        .get('/json', res => res.utf8(sJSON(json), responses.json))
        .listen('0.0.0.0', 8080)

    const clock = new Clock()
    clock.set(() => {
        server.update()
    })
}

spawn(main)
    .catch(err => just.error(err.stack))

This is working for me. But I am unable to understand the Clock class. what does it do ? What does server.update do?

Regarding spawn, I understand that each process carries the entire app (main function) in memory. every request to the server gets 1 process assigned, and every 'tick" the server processes the processes in the processes list. Is that understanding correct?

Also, I hope I don’t come across as entitled, but some basic starter documentation would be great to have. The examples seem to be very out of date, and working out a simple program is quite difficult. Maybe just this Hello World sample, with good comments can be added to the main readme and act as a great starting point for new users.

Issue Analytics

  • State:closed
  • Created a year ago
  • Reactions:1
  • Comments:9 (5 by maintainers)

github_iconTop GitHub Comments

1reaction
rishavscommented, Jun 9, 2022

Hey @billywhizz I would love to contribute. Right now though as there is no documentation, and that I am strugglingt o start out - I would be unable to add much value. That said, once you have started, and I undertand just-js better, I can chip in.

I had some suggestions regarding the structure - Maybe we can go for something like this, (which as a user, I would want for any new framework/library that I try)

  • Introduction - What is Just-js. Why Just-Js. arch overview. sample hello world program.
  • Installation
  • Fundamentals -
  • libs - summarizng the libs and the functionalities they provide
  • Environment variables - how to define and read
  • Context - Details of the Req and Res objects. setting headers. body content.
  • Routing - simple and dynamic routing examples
  • Forms
  • Cookies - example to show cookie setting via response (I know JJ doesnt supports this but would be good to show case how people can do this)
  • Session - How to do sessions. Hopefully with an example.
  • Static assets
  • Exception handling - also error reporting and takeovers.
  • Views & Templates - What should be the recommended way - even if its just string interpolation for now.
  • Debugging
  • Validation - examples of validating form responses
  • Testing - how to add tests. Would normal JS test runners work? whats the recommended way.
  • Database - which drivers to use. Connection creation and disposing. Querying. Pooling. capturing resposes into JS structs/classes. Transactions. Pagination.
  • Authentication. Basic Auth.
  • CORS
  • SSL - how to set up Https
  • encryption/crypto - this might be the base for future jwts and other token generation
  • Logging - simple logging using just print statements? or some other recommended way?
  • Cookbook - containing common recipes for simple tasks backend web devs do

Just-js being very low level would likely not be solving for many of these topics, but it might be a good idea to at least provide the recommended way of solving them (via a 3rd party library or just writing code).

Another thing, I would recommend having a Discord where the community can hang out on and ask questions. I am assuming that you would want to keep the GH issues mainly for bug reports.

1reaction
billywhizzcommented, Jun 8, 2022

hi @rishavs, the clock class is used to enable running multiple timers on the same schedule without having to create a new file descriptor for each one - a micro-optimization really. for your example, you could just as easily use.

just.setInterval(() => server.update(), 1000)

i may just move this logic into the http library itself or figure out a cleaner solution once i have time to look into it more.

server.update updates the Date field in the pre-generated standard headers for common responses as another micro-optimization, meaning these standard headers don’t have to be re-generated on every request. calling new Date() repeatedly in a tight loop has a significant impact on perf so goal is to avoid having to do that when generating standard headers for each request.

see here and here.

yes. i plan on spending time over next few weeks on documentation and adding some type definitions to get intellisense working in VsCode etc. and writing up some tutorials and updating examples. it’s in a reasonably stable state now where i think i can spend some time on this and hopefully generate some interest. let me know if you have any other suggestions or want to get involved in any way.

Read more comments on GitHub >

github_iconTop Results From Across the Web

C "Hello, World!" Program - Programiz
In this example, you will learn to print "Hello, World!" on the screen in C programming. A "Hello, World!" is a simple program...
Read more >
Hello World - Simple source code examples
Ever wondered how to write Hello World in some random programming language? Here we list examples of the Hello World program in various...
Read more >
"Hello, World!" program - Wikipedia
A "Hello, World!" program is generally a computer program that ignores any input and outputs or displays a message similar to "Hello, World!"....
Read more >
Basic example: Creating and running “Hello World” - IBM
Basic example: Creating and running “Hello World” · Run the program by entering the following command: ./hello. The result should be "Hello World!"....
Read more >
The Hello World Collection
The largest collection of Hello World programs on the Internet.
Read more >

github_iconTop Related Medium Post

No results found

github_iconTop Related StackOverflow Question

No results found

github_iconTroubleshoot Live Code

Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free

github_iconTop Related Reddit Thread

No results found

github_iconTop Related Hackernoon Post

No results found

github_iconTop Related Tweet

No results found

github_iconTop Related Dev.to Post

No results found

github_iconTop Related Hashnode Post

No results found