One place for hosting & domains

      Nodejs

      How To Use Vue.js Environment Modes with a Node.js Mock Data Layer


      The author selected Open Sourcing Mental Illness to receive a donation as part of the Write for DOnations program.

      Introduction

      When it comes to software development, there are two ends of the stack. A stack is a collection of technologies used for your software to function. Vue.js, the progressive user interface framework, is part of the frontend, the part of the stack that a user directly interacts with. This frontend is also referred to as the client and encompasses everything that is rendered in the user’s browser. Technologies such as HTML, JavaScript, and CSS are all rendered in the client. In contrast, the backend commonly interacts with data or servers through technologies like Java, Kotlin, or .NET.

      The application is the data itself, and the interface (frontend) is a way to display data meaningfully to the user for them to interact with. In the begining phase of software development, you don’t need a backend to get started. In some cases, the backend hasn’t even been created yet. In a case such as this, you can create your own local data to build your interface. Using Node environments and variables, you can toggle different datasets per environment or toggle between local data and “live” data via a network call. Having a mock data layer is useful if you do not have data yet, because it provides data to test your frontend before the backend is ready.

      By the end of this tutorial, you will have created several Node environments and toggled these datasets with Node environment variables. To illustrate these concepts, you will create a number of Vue components to visualize this data across environments.

      Prerequisites

      To complete this tutorial, you will need:

      Step 1 — Creating Environments with Modes

      Modes are an important concept when it comes to Vue CLI projects. A mode is an environment type, or a set of variables that gets loaded during a build. These variables are stored in .env files in the root directory of your project. As part of the default vue-cli-service plugin, you immediately have access to three modes. These are:

      • development: used when vue-cli-service serve is executed.
      • test: used when vue-cli-service test:unit is executed.
      • production: used when vue-cli-service build and vue-cli-service test:e2e are executed.

      Perhaps the most used mode is development mode. This is the mode that Vue.js developers use when working on their application on their local machine. This mode starts a local Node server with hot-module reloading (instant browser refreshing) enabled. The test mode, on the other hand, is a mode to run your unit tests in. Unit tests are JavaScript functions that test application methods, events, and in some cases, user interaction. The last default mode is production. This compressess all of your code and optimizes it for performance so it can be hosted on a production server.

      The project that is generated for you from Vue CLI has these commands pre-mapped to npm run serve, npm run test:unit, and npm run build.

      Each environment is associated with its own .env file, where you can put custom Node environment key/value pairs that your application can reference. You will not have these files after generating a project from the CLI, but you can add these using one command in your terminal.

      You will now generate a development environment file, which you will use later in the tutorial. Open your terminal and enter the following in the root directory of your project:

      Open the newly created file in your text editor of choice. In this file, you’ll want to explicitly define the environment type. This is a key/value pair that could be anything you want. However, it’s considered best practice to define the environment type that corresponds with the name of the .env file.

      You will be using this NODE_ENV later in the tutorial by loading different data sets depending on the environment or mode selected on build. Add the following line:

      .env.development

      NODE_ENV="development"
      

      Save and exit the file.

      The key/value pairs in this file will only affect your program when the application is in development mode. It’s important to note that Git will automatically commit these files unless you add the file in your .gitignore file or append the .local extension to the file name: .env.development.local.

      You are not limited to the standard environments that Vue.js provides. You may have several other environments that are specific to your workflow. Next, you’ll create a custom environment for a staging server.

      Start by creating the .env file for the staging environment. Open your terminal of choice and in the root directory run the following:

      In this file, create a key/value pair that’ll define the NODE_ENV of this project. You may open this file in your text editor of choice, or you can modify it using the terminal. Nano is an editor that is used in the terminal window. You may have other editors such as Vim.

      You will be using this NODE_ENV later in the tutorial by loading different data sets depending on the environment or mode selected on build.

      Add the following to the file:

      .env.staging

      NODE_ENV="staging"
      

      Save and exit the file. In nano, you can save the file with CTRL+X then CTRL+Y.

      In order to use this environment, you can register a new script in your package.json file. Open this file now.

      In the "scripts" section, add the following highlighted line:

      package.json

      {
        ...
        "scripts": {
          ...
          "staging": "vue-cli-service serve --mode staging",
        },
        ...
      }
      

      Save this file, then exit the editor.

      You’ve just created a new script that can be executed with npm run staging. The flag --mode lets Vue CLI know to use the .env.staging (or .env.staging.local) file when starting the local server.

      In this step, you created custom NODE_ENV variables for two Vue.js modes: development and staging. These modes will come in handy in the following steps when you create custom datasets for each of these modes. By running the project in one mode or the other, you can load different data sets by reading these files.

      Step 2 — Creating a Mock Data Layer

      As stated in the Introduction, you can start developing your user interface without a backend by using a mock data layer. A mock data layer is static data that is stored locally for your application to reference. When working with Vue, these data files are JavaScript objects and arrays. Where these are stored is your personal preference. For the sake of this tutorial, mock data files will be stored in a directory named data.

      In this tutorial, you’re building a “main/detail” airport browser application. In the “main” view, the user will see a number of airport codes and locations.

      In your terminal, in the root project directory, create a new directory using the mkdir command:

      Now create a .js file named airports.staging.mock.js using the touch command. Naming these files is personal preference, but it’s generally a good idea to differentiate this mock data from essential files in your app. For the sake of this tutorial, mock files will follow this naming convention: name.environment.mock.js.

      Create the file with the following command:

      • touch data/airports.staging.mock.js

      In your editor of choice, open this newly created JavaScript file and add the following array of objects:

      data/airports.staging.mock.js

      const airports = [
          {
              name: 'Cincinnati/Northern Kentucky International Airport',
              abbreviation: 'CVG',
              city: 'Hebron',
              state: 'KY'
          },
          {
              name: 'Seattle-Tacoma International Airport',
              abbreviation: 'SEA',
              city: 'Seattle',
              state: 'WA'
          },
          {
              name: 'Minneapolis-Saint Paul International Airport',
              abbreviation: 'MSP',
              city: 'Bloomington',
              state: 'MN'
          }
      ]
      
      export default airports
      

      In this code block, you are creating objects that represent airports in the United States and providing their name, abbreviation, and the city and state in which they are located. You then export the array to make it available to other parts of your program. This will act as your “staging” data.

      Next, create a dataset for another environment like “development"—the default environment when running npm run serve. To follow the naming convention, create a new file in your terminal with the touch command and name it airports.development.mock.js:

      • touch data/airports.development.mock.js

      In your editor of choice, open this newly created JavaScript file and add the following array of objects:

      data/airports.development.mock.js

      const airports = [
          {
              name: 'Louis Armstrong New Orleans International Airport',
              abbreviation: 'MSY',
              city: 'New Orleans',
              state: 'LA'
          },
          {
              name: 'Denver International Airport',
              abbreviation: 'DEN',
              city: 'Denver',
              state: 'CO'
          },
          {
              name: 'Philadelphia International Airport',
              abbreviation: 'PHL',
              city: 'Philadelphia',
              state: 'PA'
          }
      ]
      
      export default airports
      

      This will act as your "development” data when you run npm run serve.

      Now that you’ve created the mock data for your environments, in the next step, you are going to iterate or loop through that data with the v-for directive and start building out the user interface. This will give you a visual representation of the change when using the different modes.

      Step 3 — Iterating Through Mock Data in App.vue

      Now that you have your mock data, you can test out how useful environments are by iterating through this data in the App.vue component in the src directory.

      First, open up App.vue in your editor of choice.

      Once it is open, delete all of the HTML inside the template tags and remove the import statement in the script section. Also, delete the HelloWorld component in the export object. Some general styles have also been provided to make the data easier to read.

      Add the following highlighted lines to your App.vue file:

      src/App.vue

      <template>
      
      </template>
      
      <script>
      export default {
        name: 'App',
      }
      </script>
      
      <style>
      #app {
        font-family: Avenir, Helvetica, Arial, sans-serif;
        -webkit-font-smoothing: antialiased;
        -moz-osx-font-smoothing: grayscale;
        text-align: center;
        color: #2c3e50;
        margin-top: 60px;
      }
      
      .wrapper {
        display: grid;
        grid-template-columns: 1fr 1fr 1fr;
        grid-column-gap: 1rem;
        max-width: 960px;
        margin: 0 auto;
      }
      
      .airport {
        border: 3px solid;
        border-radius: .5rem;
        padding: 1rem;
      }
      
      .airport p:first-child {
        font-weight: bold;
        font-size: 2.5rem;
        margin: 1rem 0;
      <^>}
      
      .airport p:last-child {
        font-style: italic;
        font-size: .8rem;
      }
      </style>
      

      In this case, CSS Grid is being used to create these cards of airport codes into a grid of three. Notice how this grid is set up in the .wrapper class. The .airport is the card or section that contains each airport code, name, and location.

      Next, import the development mock data that was created earlier. Since this is vanilla JavaScript, you can import it via an import statement. You will also need to register this data with the data property so the Vue template has access to this data.

      Add the following highlighted lines:

      src/App.vue

      ...
      <script>
      import airports from '../data/airports.development.mock'
      
      export default {
        name: 'App',
        data() {
          return {
            airports
          }
        }
      }
      </script>
      ...
      

      Now that the mock data has been imported, you can start using it to build your interface. In the case of this application, iterate through this data with the v-for directive and display it in your template:

      src/App.vue

      <template>
        <div class="wrapper">
          <div v-for="airport in airports" :key="airport.abbreviation" class="airport">
            <p>{{ airport.abbreviation }}</p>
            <p>{{ airport.name }}</p>
            <p>{{ airport.city }}, {{ airport.state }}</p>
          </div>
        </div>
      </template>
      ...
      

      v-for in this case is used to render the list of airports.

      Save and close the file.

      In your terminal, start the development server by running the command:

      Vue CLI will provide you a local address, generally localhost:8080. Visit that addresss in your browser of choice. You will find the data from airports.development.mock.js rendered in your browser:

      Styled cards containing airport data from the development dataset.

      At this point, you created a static mock data layer and loaded it when you executed npm run serve. However, you will notice that if you stop the server (CTRL+C) and start the staging environment, you will have the same result in your browser. In this next step, you are going to tell your app to load a set of data for each environment. To achieve this, you can use a Vue computed property.

      Step 4 — Loading Environment-Specific Data with Computed Properties

      In Vue, computed properties are component functions that must return a value. These functions cannot accept arguments, and are cached by Vue. Computed properties are very useful when you need to perform logic and assign that return value to a property. In this respect, computed properties act similar to data properties as far as the template is concerned.

      In this step, you will use computed properties to use different datasets for the staging and the development environment.

      Start by opening src/App.vue and importing both sets of data:

      src/App.vue

      ...
      <script>
      import DevData from '../data/airports.development.mock'
      import StagingData from '../data/airports.staging.mock'
      
      export default {
        name: 'App',
        ...
      }
      </script>
      ...
      

      If you still have one of the environments running, your data will disappear. That is because you removed the data property that connected your JavaScript mock data to the template.

      Next, create a computed property named airports. The function name is important here because Vue is taking the return value of the function and assigning it to airports for the template to consume. In this computed property, you’ll need to write a bit of logic; an if/else statement that evaluates the Node environment name. To get the value of the Node environment in Vue, you can access it with process.env.NODE_ENV. When you created your Node environments, Vue automatically assigned NODE_ENV to development and staging respectively.

      src/App.vue

      ...
      <script>
      import DevData from '../data/airports.development.mock'
      import StagingData from '../data/airports.staging.mock'
      
      export default {
        name: 'App',
        computed: {
            airports() {
              if (process.env.NODE_ENV === 'development') return DevData
              else return StagingData
            }
        }
      }
      </script>
      ...
      

      Now you are loading each set of data per its respective environment.

      In your terminal, start the local development environment with npm run serve.

      The data will be identical to what it was before.

      Now, start the staging environment by first stopping the server and then executing npm run staging in your terminal window.

      When you visit localhost:8080 in your browser, you will find a different set of data.

      Styled cards containing airport data from the staging dataset.

      Conclusion

      In this tutorial, you worked with different Vue.js environment modes and added environment scripts to your package.json file. You also created mock data for a number of environments and iterated through the data using the v-for directive.

      By using this approach to make a temporary backend, you can focus on the development of your interface and the frontend of your application. You are also not limited to any number of environments or the default environments provided by Vue. It isn’t uncommon to have .env files for four or more environments: development, staging, user acceptance testing (UAT), and production.

      For more information on Vue.js and Vue CLI 3, it’s recommended to read through their documentation. For more tutorials on Vue, check out the Vue Topic Page.



      Source link

      Cara Memulai Ulang Aplikasi Node.js secara Otomatis dengan nodemon


      Pengantar

      Dalam Node.js, Anda perlu memulai ulang proses untuk menerapkan perubahan. Ini menambah langkah ekstra ke alur kerja Anda demi menerapkan perubahan. Anda dapat menghilangkan langkah ekstra ini dengan nodemon untuk memulai ulang prosesnya secara otomatis.

      nodemon adalah antarmuka baris-perintah (CLI) yang dikembangkan oleh @rem yang mengemas aplikasi Node Anda, memantau sistem berkas, dan secara otomatis memulai ulang proses.

      Dalam artikel ini, Anda akan mempelajari tentang menginstal, menyiapkan, dan mengonfigurasi nodemon.

      Prasyarat

      Jika Anda ingin mengikuti artikel ini, Anda membutuhkan:

      Langkah 1 — Menginstal nodemon

      Pertama, Anda perlu menginstal nodemon di mesin Anda. Instal utilitas secara global maupun secara lokal pada proyek Anda menggunakan npm atau Yarn:

      Instalasi Global

      Anda dapat menginstal nodemon secara global dengan npm:

      Atau dengan Yarn:

      Instalasi Lokal

      Anda juga dapat menginstal nodemon secara lokal dengan npm. Ketika melakukan instalasi lokal, kita dapat menginstal nodemon sebagai dependensi dev dengan --save-dev (atau --dev):

      • npm install nodemon --save-dev

      Atau dengan Yarn:

      Satu hal yang harus disadari dengan instalasi lokal adalah Anda tidak akan dapat menggunakan perintah nodemon secara langsung dari baris perintah:

      Output

      • command not found: nodemon

      Namun, Anda dapat menggunakannya sebagai bagian dari skrip npm atau dengan npx.

      Ini adalah akhir dari proses instalasi nodemon. Selanjutnya, kita akan menggunakan nodemon dengan proyek kita.

      Langkah 2 — Menyiapkan Proyek Express Contoh dengan nodemon

      Kita dapat menggunakan nodemon untuk memulai skrip Node. Misalnya, jika kita memiliki penyiapan server Express di dalam berkas server.js, kita dapat memulainya dan memantau perubahan seperti ini:

      Anda dapat memasukkan argumen dengan cara yang sama seperti Anda menjalankan skrip dengan Node:

      Setiap kali Anda membuat perubahan terhadap berkas dengan salah satu dari ekstensi asali yang dipantau (.js, .mjs, .json, .coffee, atau .litcoffee) di dalam direktori atau subdirektori saat ini, proses akan memulai ulang.

      Mari kita asumsikan kita menulis suatu berkas contoh server.js yang mengeluarkan pesan: Dolphin app listening on port ${port}!.

      Kita dapat menjalankan contoh dengan nodemon:

      Kita akan melihat keluaran terminal berikut:

      Output

      [nodemon] 1.17.3 [nodemon] to restart at any time, enter `rs` [nodemon] watching: *.* [nodemon] starting `node server.js` Dolphin app listening on port 3000!

      Sementara nodemon masih berjalan, mari kita buat perubahan terhadap berkas server.js untuk mengeluarkan pesan: Shark app listening on port ${port}!.

      Kita akan melihat keluaran terminal tambahan berikut:

      Output

      [nodemon] restarting due to changes... [nodemon] starting `node server.js` Shark app listening on port 3000!

      Keluaran terminal dari aplikasi Node.js akan menampilkan seperti yang diharapkan. Anda dapat memulai ulang prosesnya kapan pun dengan mengetik rs dan menekan ENTER.

      Sebagai alternatif, nodemon juga akan mencari berkas main yang ditentukan dalam berkas package.json dari proyek Anda:

      package.json

      {
        // ...
        "main": "server.js",
        // ...
      }
      

      Atau, skrip start:

      package.json

      {
        // ...
        "scripts": {
          "start": "node server.js"
        },
        // ...
      }
      

      Setelah Anda membuat perubahan pada package.json, Anda kemudian dapat memanggil nodemon untuk memulai aplikasi contoh di mode pemantauan tanpa harus memasukkan server.js.

      Langkah 3 — Menggunakan Opsi

      Anda dapat memodifikasi pengaturan konfigurasi yang tersedia untuk nodemon.

      Mari kita bahas beberapa opsi utama:

      • --exec: Pakai switch --exec guna menentukan biner untuk mengeksekusi berkas. Misalnya, saat dikombinasikan dengan biner ts-node, --exec dapat menjadi berguna untuk memantau perubahan dan menjalankan berkas TypeScript.
      • --ext: Menentukan ekstensi berkas berbeda yang harus dipantau. Untuk switch ini, berikan daftar ekstensi berkas yang harus dipisahkan oleh koma (misalnya, --ext js,ts).
      • --delay: Secara asali, nodemon menunggu selama satu detik untuk memulai ulang proses saat berkas berubah, tetapi dengan switch --delay, Anda dapat menentukan waktu tunggu yang berbeda. Misalnya, nodemon --delay 3.2 untuk penundaan selama 3,2 detik.
      • --watch: Gunakan switch --watch untuk menentukan beberapa direktori atau berkas yang harus dipantau. Tambahkan satu switch --watch untuk setiap direktori yang ingin Anda pantau. Secara asali, direktori dan subdirektori saat ini telah dipantau, jadi dengan --watch Anda dapat mempersempitnya hanya ke subdirektori atau berkas tertentu.
      • --ignore: Gunakan switch --ignore untuk mengabaikan berkas, pola berkas, atau direktori tertentu.
      • --verbose: Keluaran verbose yang lebih banyak dengan informasi tentang berkas-berkas yang berubah sehingga memicu pemulaian ulang.

      Anda dapat melihat semua opsi yang tersedia dengan perintah berikut:

      Dengan menggunakan opsi ini, mari kita ciptakan perintah untuk memenuhi skenario berikut:

      • memantau direktori server
      • menentukan berkas dengan ekstensi .ts
      • mengabaikan berkas dengan akhiran .test.ts
      • mengeksekusi berkas (server/server.ts) dengan ts-node
      • menunggu selama tiga detik untuk memulai ulang setelah berkas berubah
      • nodemon --watch server --ext ts --exec ts-node --ignore '*.test.ts' --delay 3 server/server.ts

      Perintah ini mengombinasikan opsi --watch, --ext, --exec, --ignore, dan --delay untuk memenuhi kondisi skenario kita.

      Langkah 4 — Menggunakan Konfigurasi

      Dalam contoh sebelumnya, menambahkan switch konfigurasi saat menjalankan nodemon bisa menjadi cukup membosankan. Solusi yang lebih baik untuk proyek yang memerlukan konfigurasi spesifik adalah dengan menentukan konfigurasi ini dalam berkas nodemon.json.

      Misalnya, ini adalah konfigurasi yang sama seperti contoh baris perintah sebelumnya, tetapi ditempatkan di dalam berkas nodemon.json:

      nodemon.json

      {
        "watch": ["server"],
        "ext": "ts",
        "ignore": ["*.test.ts"],
        "delay": "3",
        "execMap": {
          "ts": "ts-node"
        }
      }
      

      Perhatikan penggunaan execMap alih-alih switch --exec. execMap memungkinkan Anda untuk menentukan biner yang harus digunakan untuk ekstensi berkas tertentu.

      Sebagai alternatif, jika Anda lebih memilih untuk tidak menambahkan berkas konfigurasi nodemon.json ke proyek, Anda dapat menambahkan konfigurasi ini ke berkas package.json di bawah kunci nodemonConfig:

      package.json

      {
        "name": "test-nodemon",
        "version": "1.0.0",
        "description": "",
        "nodemonConfig": {
          "watch": [
            "server"
          ],
          "ext": "ts",
          "ignore": [
            "*.test.ts"
          ],
          "delay": "3",
          "execMap": {
            "ts": "ts-node"
          }
        },
        // ...
      

      Setelah Anda membuat perubahan pada nodemon.json atau package.json, Anda kemudian dapat memulai nodemon dengan skrip yang diinginkan:

      nodemon akan mengambil konfigurasinya dan menggunakannya. Dengan cara ini, konfigurasi Anda dapat disimpan, dibagikan, dan diulang untuk menghindari salin-tempel atau kesalahan tik di baris perintah.

      Kesimpulan

      Dalam artikel ini, Anda telah mendalami cara menggunakan nodemon dengan aplikasi Node.js. Alat ini membantu mengotomatiskan proses memberhentikan dan memulai server Node untuk melihat perubahan.

      Untuk informasi lebih lanjut tentang fitur dan pemecahan masalah yang tersedia, lihat dokumentasi resmi.

      Jika Anda ingin mempelajari lebih lanjut tentang Node.js, lihat laman topik Node.js. kami untuk proyek latihan dan pemrograman.





      Source link

      How To Code in Node.js eBook


      Download the Complete eBook!

      How To Code in Node.js eBook in EPUB format

      How To Code in Node.js eBook in PDF format

      Introduction to the eBook

      Node.js is a popular open-source runtime environment that can execute JavaScript outside of the browser. The Node runtime is commonly used for back-end web development, leveraging its asynchronous capabilities to create networking applications and web servers. Node is also a popular choice for building command line tools.

      In this book, you will go through exercises to learn the basics of how to code in Node.js, gaining skills that apply equally to back-end and full stack development in the process.

      By the end of this book you will be able to write programs that leverage Node’s asynchronous code execution capabilities, complete with event emitters and listeners that will respond to user actions. Along the way you will learn how to debug Node applications using the built-in debugging utilities, as well as the Chrome browser’s DevTools utilities. You will also
      learn how to write automated tests for your programs to ensure that any features that you add or change function as you expect.

      Download the eBook

      You can download the eBook in either the EPUB or PDF format by following the links below.

      Download the Complete eBook!

      How To Code in Node.js eBook in EPUB format

      How To Code in Node.js eBook in PDF format

      After you’re finished this book, if you’d like to learn more about how to build tools and applications with Node.js, visit the DigitalOcean Community’s Node.js section.



      Source link