One place for hosting & domains

      Import

      How to Dynamically Import JavaScript with Import Maps


      The author selected Creative Commons to receive a donation as part of the Write for DOnations program.

      Introduction

      External libraries can add complexity to a new JavaScript project. To be able to install and use external code libraries, you’ll need a build tool that can parse the code and bundle the libraries that you import into a final format. After the build is set up, you can add and integrate new code with ease, but there are still some problems.

      For example, you may need a library in just one part of your application, a part of the application most users may never need, like an admin page. But by default most build systems will bundle all the code into one large file. The user will load the code regardless of whether they ever need to execute it. The build systems are flexible enough that they can be configured to load code as needed, but the process takes some work.

      Build tools are an important part of the development experience, but a spec called import maps will allow you to both import external code into your project without a build tool and it will only load the code when it is needed at runtime. Import maps won’t completely replace build tools that perform many other valuable actions like building style sheets and handling images, but they will allow you to bootstrap new JavaScript applications quickly and easily using only the native browser functionality.

      In this tutorial, you’ll use import maps and JavaScript modules to import code without build tools. You’ll create a basic application that will display a message and you’ll create an import map that will tell your browser where to locate external code. Next, you’ll integrate the imported code into your JavaScript and will use the third-party code without any need to download the code locally or run it through a build step. Finally, you’ll learn about current tools that implement many aspects of import maps and work on all modern browsers.

      Prerequisites

      Step 1 — Creating an HTML Page and Inserting JavaScript

      In this step, you will create an HTML page, use JavaScript for dynamic activity, and start a local development server to track your changes.

      To start, in a new directory, create a blank HTML document.

      Open a file called index.html in a text editor:

      Inside of the file, add a short, blank HTML page:

      index.html

      <!DOCTYPE html>
      <html lang="en-US">
        <head>
          <meta charset="utf-8">
          <meta http-equiv="X-UA-Compatible" content="IE=edge">
          <title>Hello World</title>
          <meta name="viewport" content="width=device-width, initial-scale=1">
        </head>
        <body>
        </body>
      </html>
      

      This document has a few standard <meta> tags and an empty <body> element.

      Next add a <script> tag. The src attribute for the script tag will be a new JavaScript file you are about to create called hello.js:

      index.html

      <!DOCTYPE html>
      <html lang="en-US">
      <head>
        <meta charset="utf-8">
        <meta http-equiv="X-UA-Compatible" content="IE=edge">
        <title>Hello World</title>
        <meta name="viewport" content="width=device-width, initial-scale=1">
        <script defer src="https://www.digitalocean.com/community/tutorials/./hello.js"></script>
      </head>
      <body>
      </body>
      

      Notice that you are adding a defer attribute to the <script> tag. This will delay execution of the script tag until after the document is parsed. If you don’t defer, you may receive an error that says body is not found when you try to add to the element.

      Next, create a JavaScript file named hello.js in the same directory asindex.html:

      Inside of the file, write some JavaScript to create a new text element with the text "Hello, World":

      hello.js

      const el = document.createElement('h1');
      const words = "Hello, World!"
      const text = document.createTextNode(words);
      el.appendChild(text);
      
      document.body.appendChild(el);
      

      Now that you have your script, you can open the index.html file in a browser. In the same directory as your index.html file, run npx serve. This will run the serve package locally without downloading into your node_modules. The serve package runs a simple webserver that will serve your code locally.

      npx serve
      

      The command will ask you if you want to install a package. Type y to agree:

      Need to install the following packages:
        serve
      Ok to proceed? (y) y
      

      When you run the command you will see some output like this:

      npx: installed 88 in 15.187s
      
         ┌────────────────────────────────────────┐
         │                                        │
         │   Serving!                             │
         │                                        │
         │   Local:  http://localhost:5000        │
         │                                        │
         │   Copied local address to clipboard!   │
         │                                        │
         └────────────────────────────────────────┘
      
      

      When you open your web browser to http://localhost:5000, you’ll see your code. You can either leave the server running in a separate tab or window or close it with CTRL+C after previewing your code.

      Hello, World in a browser

      Now you are displaying a basic page in your browser, but you are not yet able to take advantage of third-party code and JavaScript packages. In the next step, you’ll dynamically import code and import the functions into your script without a build tool.

      Step 2 — Writing a Hello World Script Using ES6 Modules

      In this step, you’ll write code that uses external packages. You’ll modify your code to import JavaScript code using ES imports. Finally, you’ll load the code in your browser using the module type so the browser will know to dynamically load the code.

      To begin, open up hello.js:

      You are going to import some code from lodash to dynamically change your text.

      Inside of the file, change the text from Hello World to all lower case: hello world. Then at the top of the file, import the startCase function from lodash using the standard ES6 import syntax:

      hello.js

      import startCase from '@lodash/startCase';
      
      const el = document.createElement('h1');
      const words = "hello, world";
      const text = document.createTextNode(words);
      el.appendChild(text);
      
      document.body.appendChild(el);
      

      Finally, call startCase with the words variable as an argument inside of document.createTextNode:

      hello.js

      import startCase from '@lodash/startCase';
      
      const el = document.createElement('h1');
      const words = "hello, world";
      const text = document.createTextNode(startCase(words));
      el.appendChild(text);
      
      document.body.appendChild(el);
      

      If you closed your webserver, open a new terminal window or tab and run npx serve to restart the server. Then navigate to http://localhost:5000 in a web browser to view the changes.

      When you preview the code in a browser, open the developer console. When you do, you’ll see an error:

      Output

      Uncaught SyntaxError: Cannot use import statement outside a module

      Module Error

      Since the code is using import statements, you’ll need to modify the <script> tag inside of index.html to handle JavaScript that is now split between multiple files. One file is the original code you wrote. The other file is the code imported from lodash. JavaScript code that imports other code are called modules.

      Close hello.js and open index.html:

      To run the script as a module, change the value of the type attribute on the <script> tag to module:

      hello.js

      <!DOCTYPE html>
      <html lang="en-US">
      <head>
        <meta charset="utf-8">
        <meta http-equiv="X-UA-Compatible" content="IE=edge">
        <title>Hello World</title>
        <meta name="viewport" content="width=device-width, initial-scale=1">
        <script type="module" src="https://www.digitalocean.com/community/tutorials/./hello.js"></script>
      </head>
      <body>
      </body>
      </html>
      

      Notice, you also removed the defer attribute. JavaScript modules will not execute until the page is parsed.

      Open your browser and you’ll still see an error`:

      Output

      Uncaught TypeError: Failed to resolve module specifier "@lodash/startCase". Relative references must start with either "/", "./", or "../"

      Unknown specifier

      Now the problem is not the import statement. The problem is the browser doesn’t know what the import statement means. It’s expecting to find code on the webserver, so it looks for a file relative to the current file. To solve that problem, you’ll need a new tool called import maps.

      In this step, you learned how to modify your JavaScript code to load external libraries using ES imports. You also modified the HTML script tag to handle JavaScript modules.

      In the next step, you’ll tell the browser how to find code using import maps.

      Step 3 — Loading External Code with Import Maps

      In this step, you’ll learn how to create import maps to tell your browser where to find external code. You’ll also learn how to import module code and see how code is lazy-loaded in a browser.

      An import map is a JavaScript object where the key is the name of the import (@lodash/startCase) and the value is the location of the code.

      Inside of index.html add a new script tag with a type of importmap. Inside of the script tag, create a JavaScript object with a key of imports. The value will be another object:

      hello.js

      <!DOCTYPE html>
      <html lang="en-US">
      <head>
        <meta charset="utf-8">
        <meta http-equiv="X-UA-Compatible" content="IE=edge">
        <title>Hello World</title>
        <meta name="viewport" content="width=device-width, initial-scale=1">
        <script type="importmap">
          {
            "imports": {
            }
          }
        </script>
        <script type="module" src="https://www.digitalocean.com/community/tutorials/./hello.js"></script>
      </head>
      <body>
      </body>
      </html>
      

      Be sure that you do not add any trailing commas in the object. The browser will not know how to handle them.

      Now that you have your basic object, you can add the location of your code. The structure of an import map will be like this:

      {
          "imports": {
              "nameOfImport": "locationOfCode",
              "nameOfSecondImport": "secondLocation"
          }
      }
      

      You already know the name of your import @lodash/startCase, but now you need to find where a location to point the import map to.

      A great resource is unpkg. Unpkg is a content delivery network (CDN) for any package in npm. If you can npm install a package, you should be able to load it via unpkg. Unpkg also includes a browsing option that can help you find the specific file you need.

      To find the startCase code, open https://unpkg.com/browse/lodash-es@4.17.21/ in a browser. Notice the word browse in the URL. This gives you a graphical way to look through the directory, but you should not add the path to your import map since it serves up an HTML page and not the raw JavaScript file.

      Also, note that you are browsing lodash-es and not lodash. This is the lodash library exported as ES modules, which is what you will need in this case.

      Browse the code and you’ll notice there is a file called startCase.js. This code imports other functions and uses them to convert the first letter of each word to upper case:

      import createCompounder from './_createCompounder.js';
      import upperFirst from './upperFirst.js';
      
      /**
       * Converts `string` to
       * [start case](https://en.wikipedia.org/wiki/Letter_case#Stylistic_or_specialised_usage).
       *
       * @static
       * @memberOf _
       * @since 3.1.0
       * @category String
       * @param {string} [string=''] The string to convert.
       * @returns {string} Returns the start cased string.
       * @example
       *
       * _.startCase('--foo-bar--');
       * // => 'Foo Bar'
       *
       * _.startCase('fooBar');
       * // => 'Foo Bar'
       *
       * _.startCase('__FOO_BAR__');
       * // => 'FOO BAR'
       */
      var startCase = createCompounder(function(result, word, index) {
        return result + (index ? ' ' : '') + upperFirst(word);
      });
      
      export default startCase;
      

      The browser will follow the import statements and import every file necessary.

      Now that you have a location for your import map, update the file import map with the new URL. Inside of index.html, add @lodash/startCase along with the URL. Once again, be sure to remove browse:

      index.html

      <!DOCTYPE html>
      <html lang="en-US">
      <head>
        <meta charset="utf-8">
        <meta http-equiv="X-UA-Compatible" content="IE=edge">
        <title>Hello World</title>
        <meta name="viewport" content="width=device-width, initial-scale=1">
        <script type="importmap">
          {
            "imports": {
              "@lodash/startCase": "https://unpkg.com/lodash-es@4.17.21/startCase.js"
            }
          }
        </script>
        <script type="module" src="https://www.digitalocean.com/community/tutorials/./hello.js"></script>
      </head>
      <body>
      </body>
      </html>
      

      Save the file. Refresh your browser and you will see Hello World.

      Working

      NOTE: Import maps are not yet widely supported. Open the code in the latest version of Edge or Chrome or check out the latest supported browsers.

      Your browser shows “Hello World”, but now something much more interesting is happening. Open the browser console in your browser, select Inspect Elements, and switch to the Network tab.

      After opening the Network tab, refresh the page and you’ll see that the browser is loading the code dynamically. Whenever it finds a new import statement, it imports the relevant code:

      Network Tab

      More importantly, notice that all of the code is loaded lazily. That means that the browser does not import any code until it is specifically needed. For example, even though startCase is in the import map and the import map is defined before the script for hello.js, it is not loaded until after hello.js loads and imports the code.

      If you were to add other entries in your import map, the browser would not load them at all since they are never imported into code. The import map is a map of locations, and doesn’t import any code itself.

      One major problem is that import maps are not yet fully supported by all browsers. And even when they are supported, some users may not use a supported browser. Fortunately, there are different projects that use the import map syntax while adding full browser support.

      In this step you created an import map. You also learned how to import module code and how the code will be lazy loaded in the browser. In the next step, you’ll import code using SystemJS.

      Step 4 — Building Cross-Browser Support with SystemJS

      In this step, you’ll use import maps across all browsers using SystemJS. You’ll export code as a SystemJS build and how to set the import map type to use SystemJS format. By the end of this step, you’ll be able to take advantage of import maps in any browser and will have a foundation for building more complex applications and microfrontends.

      Import maps will remove many of the complicated build steps from an application, but they are not yet widely supported. Further, not all libraries are built as ES modules so there is some limitation to how you can use them in your code.

      Fortunately, there is a project called SystemJS that can use create import maps for cross-browser support and use a variety of package builds.

      The lodash library is convenient because it is compiled in an ES format, but that’s not the case for most libraries. Many libraries are exported in other formats. One of the most common is the Universal Module Definition or UMD. This format works in both browsers and node modules.

      A major difference is that unlike the ES imports, a UMD build typically combines all of the code into a single file. The file will be a lot larger and you’ll end up with more code then you’ll probably execute.

      To update your project to use SystemJS and a UMD build of lodash, first open hello.js:

      Change the import statement to import the startCase function directly from lodash.

      hello.js

      import { startCase } from 'lodash';
      
      const el = document.createElement('h1');
      const words = "hello, world";
      const text = document.createTextNode(startCase(words));
      el.appendChild(text);
      
      document.body.appendChild(el);
      

      Save and close the file.

      Next, to build the file as a SystemJS build, you will need a simple build step. You can use another build tool such as webpack, but in this example you’ll use rollup.

      First, initialize the project to create a package.json file. Add the -y flag to accept all of the defaults:

      npm init -y
      

      After the command runs you’ll see a success output:

      {
        "name": "hello",
        "version": "1.0.0",
        "description": "",
        "main": "index.js",
        "devDependencies": {},
        "scripts": {
          "test": "echo "Error: no test specified" && exit 1"
        },
        "keywords": [],
        "author": "",
        "license": "ISC",
        "homepage": ""
      }
      

      Note: Your output may be slightly different depending on the version of npm you are using.

      Next, install rollup as a devDepenceny:

      npm install --save-dev rollup
      

      After a moment, you will see a success message:

      + rollup@2.56.2
      added 1 package from 1 contributor and audited 2 packages in 6.85s
      found 0 vulnerabilities
      

      Next, create a simple build configuration. Open a new file called rollup.config.js:

      Then add a configuration that will output the code in SystemJS format:

      rollup.config.js

      export default {
        external: ["lodash"],
        input: ["hello.js"],
        output: [
          {
            dir: "public",
            format: "system",
            sourcemap: true
          }
        ]
      };
      

      The external key tells rollup not to include any of the lodash code in the final build. SystemJS will load that code dynamically when it is imported.

      The input is the location of the root file. The output tells rollup where to put the final code and the format it should use which in this case is system.

      Save and close the file.

      Now that you have a build step, you’ll need to add a task to run it. Open package.json:

      In the scripts object, add a script called build that will run rollup -c. Change the main key to hello.js:

      package.json

      {
        "name": "hello",
        "version": "1.0.0",
        "description": "",
        "main": "hello.js",
        "devDependencies": {
          "rollup": "^2.56.2"
        },
        "scripts": {
          "build": "rollup -c"
        },
        "keywords": [],
        "author": "",
        "license": "ISC",
        "homepage": ""
      }
      

      Save and close the file, and run the build command:

      npm run build
      

      The command will run briefly, then you will see a success message:

      > rollup -c
      
      
      hello.js → public...
      created public in 21ms
      
      

      You will also see a new directory called public that will contain the built file. If you open public/hello.js you’ll see your project compiled in a system format.

      The file will look like this. It’s similar to hello.js with a surrounding System.register method. In addtion, lodash is in an array. This will tell SystemJS to load the external library during run time. One of the maintainers created a video that further explains the module format.

      public/hello.js

      System.register(['lodash'], function () {
          'use strict';
          var startCase;
          return {
              setters: [function (module) {
                  startCase = module.startCase;
              }],
              execute: function () {
      
                  const el = document.createElement('h1');
                  const words = "hello, world";
                  const text = document.createTextNode(startCase(words));
                  el.appendChild(text);
      
                  document.body.appendChild(el);
      
              }
          };
      });
      //# sourceMappingURL=hello.js.map
      

      Save and close the file.

      The final step is to update your index.html to handle the new file:

      Open index.html

      First, you’ll need to import the SystemJS code. Use a regular <script> tag with the src attribute pointing to a CDN distribution.

      Put the <script> tag right below the import map:

      index.html

      <!DOCTYPE html>
      <html lang="en-US">
      <head>
        <meta charset="utf-8">
        <meta http-equiv="X-UA-Compatible" content="IE=edge">
        <title>Hello World</title>
        <meta name="viewport" content="width=device-width, initial-scale=1">
        <script type="importmap">
          {
            "imports": {
              "@lodash/startCase": "https://unpkg.com/lodash-es@4.17.21/startCase.js
            }
          }
        </script>
        <script src="https://cdn.jsdelivr.net/npm/systemjs/dist/system.js"></script>
        <script type="module" src="https://www.digitalocean.com/community/tutorials/./hello.js"></script>
      </head>
      <body>
      </body>
      </html>
      

      Next, you’ll need to update your import map. The format is similar to what you completed in Step 3, but there are three changes:

      • Update the import map type.
      • Update the reference to lodash.
      • Add a reference to the hello.js script.

      First, update the type. Since this is not the native browser version of an import map, but a systemjs version, change the type to systemjs-importmap:

      index.html

      <!DOCTYPE html>
      <html lang="en-US">
      <head>
        <meta charset="utf-8">
        <meta http-equiv="X-UA-Compatible" content="IE=edge">
        <title>Hello World</title>
        <meta name="viewport" content="width=device-width, initial-scale=1">
        <script type="systemjs-importmap">
          {
            "imports": {
              "@lodash/startCase": "https://unpkg.com/lodash-es@4.17.21/startCase.js
            }
          }
        </script>
        <script src="https://cdn.jsdelivr.net/npm/systemjs/dist/system.js"></script>
        <script type="module" src="https://www.digitalocean.com/community/tutorials/./hello.js"></script>
      </head>
      <body>
      </body>
      </html>
      

      Next, update the references. Change @lodash/startCase to lodash. You’ll be importing the full library. Then change the location to the UMD build at unpkg.

      Then add a new entry for hello and point that to the compiled version in the public directory:

      index.html

      ...
        <meta name="viewport" content="width=device-width, initial-scale=1">
        <script type="systemjs-importmap">
          {
            "imports": {
              "hello": "./public/hello.js",
              "lodash": "https://unpkg.com/lodash@4.17.21/lodash.js"
            }
          }
        </script>
      ...
      

      Now that you are importing systemJS and have updated the import maps, all that’s left is to load the module.

      Change the type attribute on the script tag for the module to systemjs-module. Then change the src to import:hello. This will tell systemjs to load the hello script and execute:

      hello.js

      ...
        <script type="systemjs-importmap">
          {
            "imports": {
              "hello": "./public/hello.js",
              "lodash": "https://unpkg.com/lodash@4.17.21/lodash.js"
            }
          }
        </script>
        <script src="https://cdn.jsdelivr.net/npm/systemjs/dist/system.js"></script>
        <script type="systemjs-module" src="https://www.digitalocean.com/community/tutorials/import:hello"></script>
      </head>
      ...
      

      Save and close the file.

      When you do, the browser will refresh and you’ll see Hello World.

      Unlike native import maps, this will work in any browser. Here’s the result in FireFox:

      Hello in firefox

      If you look at the Network tab. You’ll see that as with import maps, the code is lazy loaded as needed:

      Firefox network tab

      In this step, you used import maps across browsers with SystemJS. You changed your script to use the UMD build of lodash, created a rollup build to output the code in system format, and changed the import map and module types to work with SystemJS

      Conclusion

      In this tutorial you used import maps to dynamically load JavaScript code. You rendered an application that dynamically loaded an external library without any build step. Then, you created a build process to generate your code in SystemJS format so that you can use import maps across all browsers.

      Import maps give you opportunities to start breaking large projects into smaller independent pieces called microfronentends. You also do not need to limit yourself to statically defined maps as you learned in this tutorial; you can also create dynamic import maps that can load from other scripts. You also can use a single import map for multiple projects by using scopes to define different versions of a dependency for different scripts that import them.

      There are new features in progress and you can follow them on the official spec.



      Source link

      How To Import and Export a MongoDB Database on Ubuntu 20.04


      The author selected the COVID-19 Relief Fund to receive a donation as part of the Write for DOnations program.

      Introduction

      MongoDB is one of the most popular NoSQL database engines. It is famous for being scalable, powerful, reliable and easy to use. In this article we’ll show you how to import and export your MongoDB databases.

      We should make clear that by import and export we mean those operations that deal with data in a human-readable format, compatible with other software products. By contrast, the backup and restore operations create or use MongoDB specific binary data, which preserve the consistency and integrity of your data and also its specific MongoDB attributes. Thus, for migration it’s usually preferable to use backup and restore, as long as the source and target systems are compatible.

      Backup, restore, and migration tasks are beyond the scope of this article. For more information refer to How To Back Up, Restore, and Migrate a MongoDB Database on Ubuntu 20.04.

      Prerequisites

      To complete this tutorial you will need the following:

      Step One — Importing Information Into MongoDB

      To learn how importing information into MongoDB works let’s use a popular sample MongoDB database about restaurants. It’s in .json format and can be downloaded using wget like this:

      • wget https://raw.githubusercontent.com/mongodb/docs-assets/primer-dataset/primer-dataset.json

      Once the download completes you should have a file called primer-dataset.json (12 MB size) in the current directory. Let’s import the data from this file into a new database called newdb and into a collection called restaurants.

      Use the mongoimport command like this:

      • sudo mongoimport --db newdb --collection restaurants --file primer-dataset.json

      The result will look like this:

      Output

      2020-11-11T19:37:55.607+0000 connected to: mongodb://localhost/ 2020-11-11T19:37:57.841+0000 25359 document(s) imported successfully. 0 document(s) failed to import

      As the above command shows, 25359 documents have been imported. Because we didn’t have a database called newdb, MongoDB created it automatically.

      Let’s verify the import.

      Connect to the newly created newdb database:

      You are now connected to the newdb database instance. Notice that your prompt has changed, indicating that you are connected to the database.

      Count the documents in the restaurants collection with the command:

      The result will show 25359, which is the number of imported documents. For an even better check you can select the first document from the restaurants collection like this:

      The result will look like this:

      [secondary label Output]
      {
          "_id" : ObjectId("5fac3d937f12c471b3f26733"),
          "address" : {
              "building" : "1007",
              "coord" : [
                  -73.856077,
                  40.848447
              ],
              "street" : "Morris Park Ave",
              "zipcode" : "10462"
          },
          "borough" : "Bronx",
          "cuisine" : "Bakery",
          "grades" : [
              {
                  "date" : ISODate("2014-03-03T00:00:00Z"),
                  "grade" : "A",
                  "score" : 2
              },
      ...
          ],
          "name" : "Morris Park Bake Shop",
          "restaurant_id" : "30075445"
      }
      

      Such a detailed check could reveal problems with the documents such as their content, encoding, etc. The json format uses UTF-8 encoding and your exports and imports should be in that encoding. Have this in mind if you edit manually the json files. Otherwise, MongoDB will automatically handle it for you.

      To exit the MongoDB prompt, type exit at the prompt:

      You will be returned to the normal command line prompt as your non-root user.

      Step Two — Exporting Information From MongoDB

      As we have previously mentioned, by exporting MongoDB information you can acquire a human readable text file with your data. By default, information is exported in json format but you can also export to csv (comma separated value).

      To export information from MongoDB, use the command mongoexport. It allows you to export a very fine-grained export so that you can specify a database, a collection, a field, and even use a query for the export.

      A simple mongoexport example would be to export the restaurants collection from the newdb database which we have previously imported. It can be done like this:

      • sudo mongoexport --db newdb -c restaurants --out newdbexport.json

      In the above command, we use --db to specify the database, -c for the collection and --out for the file in which the data will be saved.

      The output of a successful mongoexport should look like this:

      Output

      2020-11-11T19:39:57.595+0000 connected to: mongodb://localhost/ 2020-11-11T19:39:58.619+0000 [###############.........] newdb.restaurants 16000/25359 (63.1%) 2020-11-11T19:39:58.871+0000 [########################] newdb.restaurants 25359/25359 (100.0%) 2020-11-11T19:39:58.871+0000 exported 25359 records

      The above output shows that 25359 documents have been imported — the same number as of the imported ones.

      In some cases you might need to export only a part of your collection. Considering the structure and content of the restaurants json file, let’s export all the restaurants which satisfy the criteria to be situated in the Bronx borough and to have Chinese cuisine. If we want to get this information directly while connected to MongoDB, connect to the database again:

      Then, use this query:

      • db.restaurants.find( { "borough": "Bronx", "cuisine": "Chinese" } )

      The results are displayed to the terminal:

      Output

      • 2020-12-03T01:35:25.366+0000 connected to: mongodb://localhost/
      • 2020-12-03T01:35:25.410+0000 exported 323 records

      To exit the MongoDB prompt, type exit:

      If you want to export the data from a sudo command line instead of while connected to the database, make the previous query part of the mongoexport command by specifying it for the -q argument like this:

      • sudo mongoexport --db newdb -c restaurants -q "{"borough": "Bronx", "cuisine": "Chinese"}" --out Bronx_Chinese_retaurants.json

      Note that we are escaping the double quotes with backslash () in the query. Similarly, you have to escape any other special characters in the query.

      If the export has been successful, the result should look like this:

      Output

      2020-11-11T19:49:21.727+0000 connected to: mongodb://localhost/ 2020-11-11T19:49:21.765+0000 exported 323 records

      The above shows that 323 records have been exported, and you can find them in the Bronx_Chinese_retaurants.json file that we specified.

      Use cat and less to scan the data:

      • cat Bronx_Chinese_retaurants.json | less

      Use SPACE to page through the data:

      Output

      • date":{"$date":"2015-01-14T00:00:00Z"},"grade":"Z","score":36}],"na{"_id":{"$oid":"5fc8402d141f5e54f9054f8d"},"address":{"building":"1236","coord":[-73.8893654,40.81376179999999],"street":"238 Spofford Ave","zipcode":"10474"},"borough":"Bronx","cuisine":"Chinese","grades":[{"date":{"$date":"2013-12-30T00:00:00Z"},"grade":"A","score":8},{"date":{"$date":"2013-01-08T00:00:00Z"},"grade":"A","score":10},{"date":{"$date":"2012-06-12T00:00:00Z"},"grade":"B","score":15}],
      • . . .

      Press q to exit. You can now import and export a MongoDB database.

      Conclusion

      This article has introduced you to the essentials of importing and exporting information to and from a MongoDB database. You can continue further reading on How To Back Up, Restore, and Migrate a MongoDB Database on Ubuntu 20.04.

      You can also consider using replication. Replication allows you to continue running your MongoDB service uninterrupted from a slave MongoDB server while you are restoring the master one from a failure. Part of the replication is the operations log (oplog), which records all the operations that modify your data. You can use this log, just as you would use the binary log in MySQL, to restore your data after the last backup has taken place. Recall that backups usually take place during the night, and if you decide to restore a backup in the evening you will be missing all the updates since the last backup.



      Source link

      Understanding Modules and Import and Export Statements in JavaScript


      The author selected the COVID-19 Relief Fund to receive a donation as part of the Write for DOnations program.

      Introduction

      In the early days of the Web, websites consisted primarily of HTML and CSS. If any JavaScript loaded into a page at all, it was usually in the form of small snippets that provided effects and interactivity. As a result, JavaScript programs were often written entirely in one file and loaded into a script tag. A developer could break the JavaScript up into multiple files, but all variables and functions would still be added to the global scope.

      But as websites have evolved with the advent of frameworks like Angular, React, and Vue, and with companies creating advanced web applications instead of desktop applications, JavaScript now plays a major role in the browser. As a result, there is a much greater need to use third-party code for common tasks, to break up code into modular files, and to avoid polluting the global namespace.

      The ECMAScript 2015 specification introduced modules to the JavaScript language, which allowed for the use of import and export statements. In this tutorial, you will learn what a JavaScript module is and how to use import and export to organize your code.

      Modular Programming

      Before the concept of modules appeared in JavaScript, when a developer wanted to organize their code into segments, they would create multiple files and link to them as separate scripts. To demonstrate this, create an example index.html file and two JavaScript files, functions.js and script.js.

      The index.html file will display the sum, difference, product, and quotient of two numbers, and link to the two JavaScript files in script tags. Open index.html in a text editor and add the following code:

      index.html

      <!DOCTYPE html>
      <html lang="en">
        <head>
          <meta charset="utf-8" />
          <meta name="viewport" content="width=device-width, initial-scale=1.0" />
      
          <title>JavaScript Modules</title>
        </head>
      
        <body>
          <h1>Answers</h1>
          <h2><strong id="x"></strong> and <strong id="y"></strong></h2>
      
          <h3>Addition</h3>
          <p id="addition"></p>
      
          <h3>Subtraction</h3>
          <p id="subtraction"></p>
      
          <h3>Multiplication</h3>
          <p id="multiplication"></p>
      
          <h3>Division</h3>
          <p id="division"></p>
      
          <script src="https://www.digitalocean.com/community/tutorials/functions.js"></script>
          <script src="https://www.digitalocean.com/community/tutorials/script.js"></script>
        </body>
      </html>
      

      This HTML will display the value of variables x and y in an h2 header, and the value of operations on those variables in the following p elements. The id attributes of the elements are set for DOM manipulation, which will happen in the script.js file; this file will also set the values of x and y. For more information on HTML, check out our How To Build a Website with HTML series.

      The functions.js file will contain the mathematical functions that will be used in the second script. Open the functions.js file and add the following:

      functions.js

      function sum(x, y) {
        return x + y
      }
      
      function difference(x, y) {
        return x - y
      }
      
      function product(x, y) {
        return x * y
      }
      
      function quotient(x, y) {
        return x / y
      }
      

      Finally, the script.js file will determine the values of x and y, apply the functions to them, and display the result:

      script.js

      
      const x = 10
      const y = 5
      
      document.getElementById('x').textContent = x
      document.getElementById('y').textContent = y
      
      document.getElementById('addition').textContent = sum(x, y)
      document.getElementById('subtraction').textContent = difference(x, y)
      document.getElementById('multiplication').textContent = product(x, y)
      document.getElementById('division').textContent = quotient(x, y)
      

      After setting up these files and saving them, you can open index.html in a browser to display your website with all the results:

      Rendered HTML with the values 10 and 5 and the results of the functions.js operations.

      For websites with a few small scripts, this is an effective way to divide the code. However, there are some issues associated with this approach, including:

      • Polluting the global namespace: All the variables you created in your scripts—sum, difference, etc.—now exist on the window object. If you attempted to use another variable called sum in another file, it would become difficult to know which value would be used at any point in the scripts, since they would all be using the same window.sum variable. The only way a variable could be private was by putting it within a function scope. There could even be a conflict between an id in the DOM named x and var x.
      • Dependency management: Scripts would have to be loaded in order from top to bottom to ensure the correct variables were available. Saving the scripts as different files gives the illusion of separation, but it is essentially the same as having a single inline <script> in the browser page.

      Before ES6 added native modules to the JavaScript language, the community attempted to come up with several solutions. The first solutions were written in vanilla JavaScript, such as writing all code in objects or immediately invoked function expressions (IIFEs) and placing them on a single object in the global namespace. This was an improvement on the multiple script approach, but still had the same problems of putting at least one object in the global namespace, and did not make the problem of consistently sharing code between third parties any easier.

      After that, a few module solutions emerged: CommonJS, a synchronous approach that was implemented in Node.js, Asynchronous Module Definition (AMD), which was an asynchronous approach, and Universal Module Definition (UMD), which was intended to be a universal approach that supported both previous styles.

      The advent of these solutions made it easier for developers to share and reuse code in the form of packages, modules that can be distributed and shared, such as the ones found on npm. However, since there were many solutions and none were native to JavaScript, tools like Babel, Webpack, or Browserify had to be implemented to use modules in browsers.

      Due to the many problems with the multiple file approach and the complexity of the solutions proposed, developers were interested in bringing the modular programming approach to the JavaScript language. Because of this, ECMAScript 2015 supports the use of JavaScript modules.

      A module is a bundle of code that acts as an interface to provide functionality for other modules to use, as well as being able to rely on the functionality of other modules. A module exports to provide code and imports to use other code. Modules are useful because they allow developers to reuse code, they provide a stable, consistent interface that many developers can use, and they do not pollute the global namespace.

      Modules (sometimes referred to as ECMAScript modules or ES Modules) are now available natively in JavaScript, and in the rest of this tutorial you will explore how to use and implement them in your code.

      Native JavaScript Modules

      Modules in JavaScript use the import and export keywords:

      • import: Used to read code exported from another module.
      • export: Used to provide code to other modules.

      To demonstrate how to use this, update your functions.js file to be a module and export the functions. You will add export in front of each function, which will make them available to any other module.

      Add the following highlighted code to your file:

      functions.js

      export function sum(x, y) {
        return x + y
      }
      
      export function difference(x, y) {
        return x - y
      }
      
      export function product(x, y) {
        return x * y
      }
      
      export function quotient(x, y) {
        return x / y
      }
      

      Now, in script.js, you will use import to retrieve the code from the functions.js module at the top of the file.

      Note: import must always be at the top of the file before any other code, and it is also necessary to include the relative path (./ in this case).

      Add the following highlighted code to script.js:

      script.js

      
      import { sum, difference, product, quotient } from './functions.js'
      
      const x = 10
      const y = 5
      
      document.getElementById('x').textContent = x
      document.getElementById('y').textContent = y
      
      document.getElementById('addition').textContent = sum(x, y)
      document.getElementById('subtraction').textContent = difference(x, y)
      document.getElementById('multiplication').textContent = product(x, y)
      document.getElementById('division').textContent = quotient(x, y)
      

      Notice that individual functions are imported by naming them in curly braces.

      In order to ensure this code gets loaded as a module and not a regular script, add type="module" to the script tags in index.html. Any code that uses import or export must use this attribute:

      index.html

      ...
      <script type="module" src="https://www.digitalocean.com/community/tutorials/functions.js"></script>
      <script type="module" src="https://www.digitalocean.com/community/tutorials/script.js"></script>
      

      At this point, you will be able to reload the page with the updates and the website will now use modules. Browser support is very high, but caniuse is available to check which browsers support it. Note that if you are viewing the file as a direct link to a local file, you will encounter this error:

      Output

      Access to script at 'file:///Users/your_file_path/script.js' from origin 'null' has been blocked by CORS policy: Cross-origin requests are only supported for protocol schemes: http, data, chrome, chrome-extension, chrome-untrusted, https.

      Because of the CORS policy, Modules must be used in a server environment, which you can set up locally with http-server or on the internet with a hosting provider.

      Modules are different from regular scripts in a few ways:

      • Modules do not add anything to the global (window) scope.
      • Modules always are in strict mode.
      • Loading the same module twice in the same file will have no effect, as modules are only executed once.
      • Modules require a server environment.

      Modules are still often used alongside bundlers like Webpack for increased browser support and additional features, but they are also available for use directly in browsers.

      Next, you will explore some more ways in which the import and export syntax can be used.

      Named Exports

      As demonstrated earlier, using the export syntax will allow you to individually import values that have been exported by their name. For example, take this simplified version of functions.js:

      functions.js

      export function sum() {}
      export function difference() {}
      

      This would let you import sum and difference by name using curly braces:

      script.js

      import { sum, difference } from './functions.js'
      

      It is also possible to use an alias to rename the function. You might do this to avoid naming conflicts within the same module. In this example, sum will be renamed to add and difference will be renamed to subtract.

      script.js

      import {
        sum as add,
        difference as subtract
      } from './functions.js'
      
      add(1, 2) // 3
      

      Calling add() here will yield the result of the sum() function.

      Using the * syntax, you can import the contents of the entire module into one object. In this case, sum and difference will become methods on the mathFunctions object.

      script.js

      import * as mathFunctions from './functions.js'
      
      mathFunctions.sum(1, 2) // 3
      mathFunctions.difference(10, 3) // 7
      

      Primitive values, function expressions and definitions, asynchronous functions, classes, and instantiated classes can all be exported, as long as they have an identifier:

      // Primitive values
      export const number = 100
      export const string = 'string'
      export const undef = undefined
      export const empty = null
      export const obj = { name: 'Homer' }
      export const array = ['Bart', 'Lisa', 'Maggie']
      
      // Function expression
      export const sum = (x, y) => x + y
      
      // Function definition
      export function difference(x, y) {
        return x - y
      }
      
      // Asynchronous function
      export async function getBooks() {}
      
      // Class
      export class Book {
        constructor(name, author) {
          this.name = name
          this.author = author
        }
      }
      
      // Instantiated class
      export const book = new Book('Lord of the Rings', 'J. R. R. Tolkien')
      

      All of these exports can be successfully imported. The other type of export that you will explore in the next section is known as a default export.

      Default Exports

      In the previous examples, you exported multiple named exports and imported them individually or as one object with each export as a method on the object. Modules can also contain a default export, using the default keyword. A default export will not be imported with curly brackets, but will be directly imported into a named identifier.

      For example, take the following contents for the functions.js file:

      functions.js

      export default function sum(x, y) {
        return x + y
      }
      

      In the script.js file, you could import the default function as sum with the following:

      script.js

      import sum from './functions.js'
      
      sum(1, 2) // 3
      

      This can be dangerous, as there are no restrictions on what you can name a default export during the import. In this example, the default function is imported as difference although it is actually the sum function:

      script.js

      import difference from './functions.js'
      
      difference(1, 2) // 3
      

      For this reason, it is often preferred to use named exports. Unlike named exports, default exports do not require an identifier—a primitive value by itself or anonymous function can be used as a default export. Following is an example of an object used as a default export:

      functions.js

      export default {
        name: 'Lord of the Rings',
        author: 'J. R. R. Tolkien',
      }
      

      You could import this as book with the following:

      script.js

      import book from './functions.js'
      

      Similarly, the following example demonstrates exporting an anonymous arrow function as the default export:

      functions.js

      export default () => 'This function is anonymous'
      

      This could be imported with the following script.js:

      script.js

      import anonymousFunction from './functions.js'
      

      Named exports and default exports can be used alongside each other, as in this module that exports two named values and a default value:

      functions.js

      export const length = 10
      export const width = 5
      
      export default function perimeter(x, y) {
        return 2 * (x + y)
      }
      

      You could import these variables and the default function with the following:

      script.js

      import calculatePerimeter, { length, width } from './functions.js'
      
      calculatePerimeter(length, width) // 30
      

      Now the default value and named values are both available to the script.

      Conclusion

      Modular programming design practices allow you to separate code into individual components that can help make your code reusable and consistent, while also protecting the global namespace. A module interface can be implemented in native JavaScript with the import and export keywords.

      In this article, you learned about the history of modules in JavaScript, how to separate JavaScript files into multiple top-level scripts, how to update those files using a modular approach, and the import and export syntax for named and default exports.

      To learn more about modules in JavaScript, read Modules on the Mozilla Developer Network. If you’d like to explore modules in Node.js, try our How To Create a Node.js Module tutorial.



      Source link