External Functions
Learning objectives
- You know how to import code from online locations.
- You know how to determine where the code downloaded to the local computer is placed.
- You know some addresses from where you can search for libraries and functions.
Importing external functions
Previously, we learned how to import and export functions when working with multiple files. In practice, when working on larger applications, in addition to our own code, we rely on functionality implemented by others. Deno supports importing code from practically any online location.
As an example, let us use the code at https://raw.githubusercontent.com/FITech101/simplejs/main/fun-code.js, which is as follows:
const hello = () => {
console.log("Hello external function!");
};
export { hello };
Importing external functions works similarly to importing functions from local files. Now, instead of using a file as the location from where functions are imported from, we use the address of the file that has the functions that we wish to import. The example below shows how the code at https://raw.githubusercontent.com/FITech101/simplejs/main/fun-code.js can be imported and used.
import { hello } from "https://raw.githubusercontent.com/FITech101/simplejs/main/fun-code.js";
hello();
Let's assume that the above code is in a file called app.js
. When we run the app.js
for the first time, the code that needs to be imported is downloaded to the local computer and then executed. On subsequent runs, there is no longer a need to download the code, as it has already been downloaded.
deno run app.js
Download https://raw.githubusercontent.com/FITech101/simplejs/main/fun-code.js
Hello external function!
deno run app.js
Hello external function!
If the code in the online location changes but the address stays the same, our application does not know about it. In such a case, we need to clear the code that has been downloaded to our computer. We can identify the location into which code is downloaded using the command deno info
.
deno info
DENO_DIR location: "/path-to-cache/.cache/deno"
Remote modules cache: "/path-to-cache/.cache/deno/deps"
TypeScript compiler cache: "/path-to-cache/.cache/deno/gen"
The remote modules (or functions) are -- in our case -- in the path /path-to-cache/.cache/deno/deps
. If we would wish to clear the file that we just downloaded, we would have to remove it from the directory.
Typically, however, addresses also contain information about the version of the functions. The version numbers are used to keep track of changes and also to avoid the problem with downloaded code being out of date.
On code at online locations
Note that any code can be posted online. It is up to you to make sure that the code that your application depends on is safe. In this course, we will rely on Deno's standard library (https://deno.land/std) and third-party modules hosted e.g. at https://deno.land/x, https://nest.land/, and https://jspm.org/.