Gregor
    • Create new note
    • Create a note from template
      • Sharing URL Link copied
      • /edit
      • View mode
        • Edit mode
        • View mode
        • Book mode
        • Slide mode
        Edit mode View mode Book mode Slide mode
      • Customize slides
      • Note Permission
      • Read
        • Only me
        • Signed-in users
        • Everyone
        Only me Signed-in users Everyone
      • Write
        • Only me
        • Signed-in users
        • Everyone
        Only me Signed-in users Everyone
      • Engagement control Commenting, Suggest edit, Emoji Reply
    • Invite by email
      Invitee

      This note has no invitees

    • Publish Note

      Share your work with the world Congratulations! 🎉 Your note is out in the world Publish Note

      Your note will be visible on your profile and discoverable by anyone.
      Your note is now live.
      This note is visible on your profile and discoverable online.
      Everyone on the web can find and read all notes of this public team.
      See published notes
      Unpublish note
      Please check the box to agree to the Community Guidelines.
      View profile
    • Commenting
      Permission
      Disabled Forbidden Owners Signed-in users Everyone
    • Enable
    • Permission
      • Forbidden
      • Owners
      • Signed-in users
      • Everyone
    • Suggest edit
      Permission
      Disabled Forbidden Owners Signed-in users Everyone
    • Enable
    • Permission
      • Forbidden
      • Owners
      • Signed-in users
    • Emoji Reply
    • Enable
    • Versions and GitHub Sync
    • Note settings
    • Note Insights
    • Engagement control
    • Transfer ownership
    • Delete this note
    • Save as template
    • Insert from template
    • Import from
      • Dropbox
      • Google Drive
      • Gist
      • Clipboard
    • Export to
      • Dropbox
      • Google Drive
      • Gist
    • Download
      • Markdown
      • HTML
      • Raw HTML
Menu Note settings Versions and GitHub Sync Note Insights Sharing URL Create Help
Create Create new note Create a note from template
Menu
Options
Engagement control Transfer ownership Delete this note
Import from
Dropbox Google Drive Gist Clipboard
Export to
Dropbox Google Drive Gist
Download
Markdown HTML Raw HTML
Back
Sharing URL Link copied
/edit
View mode
  • Edit mode
  • View mode
  • Book mode
  • Slide mode
Edit mode View mode Book mode Slide mode
Customize slides
Note Permission
Read
Only me
  • Only me
  • Signed-in users
  • Everyone
Only me Signed-in users Everyone
Write
Only me
  • Only me
  • Signed-in users
  • Everyone
Only me Signed-in users Everyone
Engagement control Commenting, Suggest edit, Emoji Reply
  • Invite by email
    Invitee

    This note has no invitees

  • Publish Note

    Share your work with the world Congratulations! 🎉 Your note is out in the world Publish Note

    Your note will be visible on your profile and discoverable by anyone.
    Your note is now live.
    This note is visible on your profile and discoverable online.
    Everyone on the web can find and read all notes of this public team.
    See published notes
    Unpublish note
    Please check the box to agree to the Community Guidelines.
    View profile
    Engagement control
    Commenting
    Permission
    Disabled Forbidden Owners Signed-in users Everyone
    Enable
    Permission
    • Forbidden
    • Owners
    • Signed-in users
    • Everyone
    Suggest edit
    Permission
    Disabled Forbidden Owners Signed-in users Everyone
    Enable
    Permission
    • Forbidden
    • Owners
    • Signed-in users
    Emoji Reply
    Enable
    Import from Dropbox Google Drive Gist Clipboard
       owned this note    owned this note      
    Published Linked with GitHub
    Subscribed
    • Any changes
      Be notified of any changes
    • Mention me
      Be notified of mention me
    • Unsubscribe
    Subscribe
    # Engineering --- ![node_modules](https://i.redd.it/tfugj4n3l6ez.png) --- ## Modules Modular code is code which is separated into independent modules. The idea is that internal details of individual modules should be hidden behind a public interface, making each module easier to understand, test and refactor independently of others. --- ### Core Modules Node.js has several modules compiled into the binary. 1. http 2. url 3. querystring 4. path 5. fs (file system) 6. util --- The core modules are defined within Node.js's source and are located in the lib/ folder. Core modules are always preferentially loaded if their identifier is passed to require(). For instance, require('http') will always return the built in HTTP module, even if there is a file by that name. ```javascript= const module = require('module_name'); ``` --- ### Local modules Local modules are modules created locally in your Node.js application. These modules include different functionalities of your application in separate files and folders. You can also package it and distribute it via NPM, so that Node.js community can use it. For example, if you need to connect to MongoDB and fetch data then you can create a module for it, which can be reused in your application. --- In the Node.js module system, each file is treated as a separate module. For example, consider a file named foo.js: ```javascript= const circle = require('./circle.js'); console.log(`The area of a circle of radius 4 is ${circle.area(4)}`); ``` On the first line, foo.js loads the module circle.js that is in the same directory as foo.js. --- Here are the contents of circle.js: ```javascript= const { PI } = Math; exports.area = (r) => PI * r ** 2; exports.circumference = (r) => 2 * PI * r; ``` --- The module circle.js has exported the functions area() and circumference(). Functions and objects are added to the root of a module by specifying additional properties on the special exports object. Variables local to the module will be private, because the module is wrapped in a function by Node.js. In this example, the variable PI is private to circle.js. The module.exports property can be assigned a new value (such as a function or object). --- ### The module.exports or exports is a special object which is included in every JS file in the Node.js application by default. module is a variable that represents current module and exports is an object that will be exposed as a module. So, whatever you assign to module.exports or exports, will be exposed as a module. --- ### Modules in the browser ![browser support](https://miro.medium.com/max/1400/1*lZEwgfn5Zhi3nCaHA04tPA.png) --- ```html= <script type="module" src="./main.js"></script> <script type="module"> import {log} from './main.js'; log('Inline module!'); </script> ``` --- ## Asynchonrous functions ![callback](https://i.imgur.com/x5cZAM3.jpg) --- ### Why should you use asyncronous forms of functions wherever possible in Node? ![loading](https://media.giphy.com/media/3oEjI6SIIHBdRxXI40/giphy.gif) --- Because I/O is sloooow ![callback1](https://i.imgur.com/weYyHkG.png) --- ### What are error-first callbacks, and why is it important to follow that pattern in your own code? It's a pattern! ```javascript fs.readFile('/foo.txt', function(err, data) { // If an error occurred, handle it (throw, propagate, etc) if(err) { console.log('Unknown Error'); return; } // Otherwise, log the file contents console.log(data); }); ``` --- ### Why should you avoid using throw in callbacks? Asynchronous exception is uncatchable because the intended catch block is not present when the asynchronous code is executed. Instead, the exception will propagate all the way and terminate the program. --- ### When might you use the syncronous form of a function instead? ![image alt](https://media.giphy.com/media/yR4xZagT71AAM/giphy.gif) --- ## Input / Output ### The FS and Path Modules --- The Node.js file system module allows you to work with the file system on your computer. It provides an API for interacting with the file system in a manner closely modeled around standard POSIX functions. --- To use this module use: `const fs = require("fs")` --- Common use for the File System module: - Read files - Create files - Update files - Delete files - Rename files --- ### Read Files Read files such as HTML and host them online The fs.readFile() method is used to read files on your computer. --- ### Create Files The File System module has methods for creating new files: fs.appendFile() fs.open() fs.writeFile() --- ### Update Files The File System module has methods for updating files: fs.appendFile() fs.writeFile() --- ### Delete Files To delete a file with the File System module, use the fs.unlink() method. --- ### Rename Files To rename a file with the File System module, use the fs.rename() method. --- ## What are some of the issues of working with paths when accessing a file system? --- ![](https://media.giphy.com/media/l4Ki4tqdPaBWaVDY4/giphy.gif) - Structuring files into logical paths & keeping them in distinct, well-defined folders --- - names, naming files - Not good for modularising, if you change the folder names... uh, oh! --- - There are functions available in paths module which you'd be hardcoding, i.e. time-wasting! ![](https://media.giphy.com/media/FOHj4MpT2PLm8/giphy.gif) - No need to install paths, it is part of core modules --- ![](https://media.giphy.com/media/xUPGcM9CazM9H5KrEA/giphy.gif) --- The Path module provides a way of working with directories and file paths. --- To use the module: `var path = require('path');` --- ![](https://i.imgur.com/sM94eoW.png) --- ## Some Cool 1'z ![](https://media.giphy.com/media/3o7abHGYSCrtVws2Os/giphy.gif) --- The path.basename() methods returns the last portion of a path. ```javascript= path.basename('/foo/bar/baz/asdf/quux.html'); // Returns: 'quux.html' ``` ```javascript= path.basename('/foo/bar/baz/asdf/quux.html', '.html');` `// Returns: 'quux' ``` --- The path.dirname() method returns the directory name of a path. ```javascript= path.dirname('/foo/bar/baz/asdf/quux'); // Returns: '/foo/bar/baz/asdf' ``` --- The path.extname() method returns the extension of the path, from the last occurrence of the . (period) character to end of string in the last portion of the path. ```javascript= path.extname('index.html') //Returns: '.html' ``` --- ## Working with URLS --- ### What is a urlObject and how is it structured? - A URL like ``` http://www.example.com/foo?bar=1#main ``` consists of several different parts - e.g., the host part ``` (www.example.com) ``` or the search ``` (?bar=1, often called query string) ``` --- - When writing Node.js web server software, you regularly need to access or even manipulate those different parts. - splitting this string into its different logical parts manually with substring operations or regular expressions is very cumbersome. - A dedicated library makes this very easy. --- - the url module provides a parse() method which converts a url string into a urlObject - The parsed urlObject has various properties denoting different parts of the url ```javascript= var url=require('url'); var address = "http://gremlin:sparks@host.domain.com:4444/somewhere?q=one"; var my_url=url.parse(address); ``` my_url will be the following object ```javascript= { protocol: "http:" host: "gremlin:sparks@host.domain.com:4444" hostname:"host.domain.com" port: "4444" auth: "gremlin:sparks" pathname: "/somewhere" search:"?q=one" query:"q=one" } ``` --- Note the query property: anything that comes after the first ? in the url is the 'query string' ``` http://example.com/path/to/page?name=ferret&color=purple the query string here is "name=ferret&color=purple" ``` this can have any number of different properties and values depending on the webpage node provides another module called querystring to separate these properties into an object --- In conclusion, the url module, especiall url.parse is useful to build functionality that depends on different parts of a url. for example to separate an endpoint from the url, or to separate the query string from the url. basically we have convenient access to the different parts of a url as object properties and values so we can use them within our code. --- ### Why is it important to be able to turn JavaScript objects into querystrings and back again? --- one of the original use cases for query strings was web forms. when we submit a form, the text entered in different fields is encoded into the url as ``` field1=value1&field2=value2&field3=value3 ``` the querystring module allows us to convert this to a JSON object using querystring.parse() and back into a string, using querystring.stringify() --- ``` field1=value1&field2=value2&field3=value3 ``` querystring.parse() would turn the above string into an object like this: ```javascript= { field1: value1, field2: value2, field3: value3 } ``` --- - having these properties as object values makes it much easier to use them in logical expressions like if statements, - or to pass these into functions that process them - (taking the CMS example from the nodegirls workshop, to take the form info and populate a blogpost on the page with these values) --- ### Why is it a bad idea to build a query string manually from other strings (think about URL encoding and escape characters)? --- Take a look at this hypothetical input into a textbox ``` chocolate is cool 8628^#^#^#*9@(*& ``` the query string version of that string would look like this ``` chocolate+is+cool+8628%5E%23%5E%23%5E%23%2A9%40%28%2A%26+ ``` this is a process known as url encoding. special characters are 'escaped' so the browser can read them properly. --- - basically A URL is composed from a limited set of characters belonging to the US-ASCII character set. These characters include digits (0-9), letters(A-Z, a-z), and a few special characters ("-", ".", "_", "~"). - there are also some 'reserved' characters that have special meaning within URLs. - examples include ```?, /, #, : ``` - any parts of the url containing data(pathname, querystring etc)must not contain these characters. --- - So keeping these limitations in mind, other special characters are 'escaped'(converted) to their hex counterparts(these start with a %), and spaces are converted to a '+' in query strings. - if we were to convert something(say form data) manually to a query string, we'd have to painstakingly create functionality to replace all these special characters with their hex keys, and spaces with '+' - using the built in stringify() method is much easier in this case. --- ## THANK YOU!! --- ## References [NodeJS documentation - modules](https://nodejs.org/api/modules.html) [NodeJS modules](https://www.tutorialsteacher.com/nodejs/nodejs-modules) [ES6 modules in the browser](https://medium.com/ghostcoder/using-es6-modules-in-the-browser-5dce9ca9e911) [W3 Schools File System](https://www.w3schools.com/nodejs/nodejs_filesystem.asp)

    Import from clipboard

    Paste your markdown or webpage here...

    Advanced permission required

    Your current role can only read. Ask the system administrator to acquire write and comment permission.

    This team is disabled

    Sorry, this team is disabled. You can't edit this note.

    This note is locked

    Sorry, only owner can edit this note.

    Reach the limit

    Sorry, you've reached the max length this note can be.
    Please reduce the content or divide it to more notes, thank you!

    Import from Gist

    Import from Snippet

    or

    Export to Snippet

    Are you sure?

    Do you really want to delete this note?
    All users will lose their connection.

    Create a note from template

    Create a note from template

    Oops...
    This template has been removed or transferred.
    Upgrade
    All
    • All
    • Team
    No template.

    Create a template

    Upgrade

    Delete template

    Do you really want to delete this template?
    Turn this template into a regular note and keep its content, versions, and comments.

    This page need refresh

    You have an incompatible client version.
    Refresh to update.
    New version available!
    See releases notes here
    Refresh to enjoy new features.
    Your user state has changed.
    Refresh to load new user state.

    Sign in

    Forgot password

    or

    By clicking below, you agree to our terms of service.

    Sign in via Facebook Sign in via Twitter Sign in via GitHub Sign in via Dropbox Sign in with Wallet
    Wallet ( )
    Connect another wallet

    New to HackMD? Sign up

    Help

    • English
    • 中文
    • Français
    • Deutsch
    • 日本語
    • Español
    • Català
    • Ελληνικά
    • Português
    • italiano
    • Türkçe
    • Русский
    • Nederlands
    • hrvatski jezik
    • język polski
    • Українська
    • हिन्दी
    • svenska
    • Esperanto
    • dansk

    Documents

    Help & Tutorial

    How to use Book mode

    Slide Example

    API Docs

    Edit in VSCode

    Install browser extension

    Contacts

    Feedback

    Discord

    Send us email

    Resources

    Releases

    Pricing

    Blog

    Policy

    Terms

    Privacy

    Cheatsheet

    Syntax Example Reference
    # Header Header 基本排版
    - Unordered List
    • Unordered List
    1. Ordered List
    1. Ordered List
    - [ ] Todo List
    • Todo List
    > Blockquote
    Blockquote
    **Bold font** Bold font
    *Italics font* Italics font
    ~~Strikethrough~~ Strikethrough
    19^th^ 19th
    H~2~O H2O
    ++Inserted text++ Inserted text
    ==Marked text== Marked text
    [link text](https:// "title") Link
    ![image alt](https:// "title") Image
    `Code` Code 在筆記中貼入程式碼
    ```javascript
    var i = 0;
    ```
    var i = 0;
    :smile: :smile: Emoji list
    {%youtube youtube_id %} Externals
    $L^aT_eX$ LaTeX
    :::info
    This is a alert area.
    :::

    This is a alert area.

    Versions and GitHub Sync
    Get Full History Access

    • Edit version name
    • Delete

    revision author avatar     named on  

    More Less

    Note content is identical to the latest version.
    Compare
      Choose a version
      No search result
      Version not found
    Sign in to link this note to GitHub
    Learn more
    This note is not linked with GitHub
     

    Feedback

    Submission failed, please try again

    Thanks for your support.

    On a scale of 0-10, how likely is it that you would recommend HackMD to your friends, family or business associates?

    Please give us some advice and help us improve HackMD.

     

    Thanks for your feedback

    Remove version name

    Do you want to remove this version name and description?

    Transfer ownership

    Transfer to
      Warning: is a public team. If you transfer note to this team, everyone on the web can find and read this note.

        Link with GitHub

        Please authorize HackMD on GitHub
        • Please sign in to GitHub and install the HackMD app on your GitHub repo.
        • HackMD links with GitHub through a GitHub App. You can choose which repo to install our App.
        Learn more  Sign in to GitHub

        Push the note to GitHub Push to GitHub Pull a file from GitHub

          Authorize again
         

        Choose which file to push to

        Select repo
        Refresh Authorize more repos
        Select branch
        Select file
        Select branch
        Choose version(s) to push
        • Save a new version and push
        • Choose from existing versions
        Include title and tags
        Available push count

        Pull from GitHub

         
        File from GitHub
        File from HackMD

        GitHub Link Settings

        File linked

        Linked by
        File path
        Last synced branch
        Available push count

        Danger Zone

        Unlink
        You will no longer receive notification when GitHub file changes after unlink.

        Syncing

        Push failed

        Push successfully