Node vs HTML

I thought I'd take a post to just lay out something I know, and maybe drop a few related facts along the way.

HTML script tags

HTML documents import files into the browser via <script> elements in the document head. Actually, that's not totally true. The elements can be inserted anywhere in the document (as far as I know -- which isn't very far. Perhaps this should say anywhere between the <html> tags..but even then I doubt how accurate I'd be).

Generally, you'll see them up in the <head> of the document, before the <body>. On occasion you'll see them somewhere inside, but at the bottom of, the body of the file. That's because scripts are loaded when and where they're rendered (or read? or interpreted?) and if the script depends on something that has not yet loaded, the javascript within that file will be unable to locate that something and act on it.

In other words, if a script needs an element to exist, you can place the script in the document below the element. That way the element will exist and the .js won't be looking for something that doesn't yet exist.

Here's another fact: scripts are executed once they're loaded. So a variable that exists within the script's global scope will be available within the document's global scope.

Here's a demonstration:

<!DOCTYPE html>
    <script src="example.js"></script

var exampleVariable = 'check this out'

In the console of your browser's developer tools you can access the code within your script. Simple as this:

//in browser console

> 'check this out'

And here, let's demonstrate that the 'window' is the global object (read: global scope) inside the browser.

//in browser console

> 'check this out'

If you have multiple scripts, they can interact with each other because the browser imports and executes them all within one environment.

Let's relate this to node

Node isn't a browser. It's an environment that allows you to run javascript outside of the browser.

So without having access to script tags, how can you provide files access to each other?

Node provides two complementary tools that allow files to interact: export and require.

They work like this:

var exampleVariable = 'hey look!'

var exampleFunction = () => return 'check this out'

exports.exampleVariable = exampleVariable
exports.exampleFunction = exampleFunction

var imported = require('./thisFileExportsThings')


>'hey look!'
>'check this out'

And finally Python

Python follows a similar syntax. The only difference is that python's import statement does double duty, handling the work of both of require() and exports from javascript.

def example_func():
  print('python is great')

import exporting_file

>'python is great'