The I in I/O!
Goals:
- Import data from an external file—from anywhere on the web—using Pencil Code's
load
function - Learn more about coding with asynchronous processes
Coding Snippets:
load
accepts two arguments, a filename and a callback.load
invokes the callback upon completion of the data import.load
passes data to the callback via its single argument (here, nameddata
) as a single String. This example uses the Stringsplit
method to separate that String into an array of String values, which it then converts to Numbers usingparseInt
.
Math and Computer Concepts:
- The hypertext transfer protocol (HTTP) underlies nearly all interaction between a web page viewed in a computer's browser and the server(s) that provide the information that comprise that page.
- Web browsers interact with external files using HTTP requests. Making HTTP requests with plain JavaScript or even with jQuery enhancements can be tricky. Pencil Code facilitates reading and writing to files on the web with its custom
load
andsave
functions.
- HTTP requests are made asynchronously. This means that JavaScript starts the loading process and then moves on to process other code while waiting for the data transfer to complete. Use the
await
anddefer
functions as illustrated below to force your program to wait for the asynchronous load process to complete before moving on to subsequent code in your script:
Activities:
Save each of the following in a folder called IO.
- Construct a CodingInstructor program which instructs users to select from a menu of programs that you have previously written, so that they can learn from your example! Based on the user input, your program should load the code from the corresponding pencilcode.net file and display it on screen.
- Asynchronicity: write a script that illustrates that
load
runs ansyncronously, i.e., in the background while your program continues processing subsequent lines of code, without waiting for the load process to complete. Do this by displaying calls toDate.now()
before and after the call toload
and also from within the callback passed toload
(which is called when the load process is finished). - Write a program that tells random DadJokes using the jokes saved in https://hacker.pencilcode.net/code/41-IO/DadJokes.txt. Before you tell jokes, you will need to process the imported data. Divide the string into an array using the
split
method, using the newline character as a delimeter (as illustrated in the lesson's coding snippet). Then usesplit
again to break up each line into a question and an answer—but this time you will need to use a different delimeter. (Hint: look in the source file to see what it is!)