Code Monkey home page Code Monkey logo

md-links's Introduction

MD-Links

Index

  1. Preamble
  2. Project Summary
  3. Project Development 3.1 Milestone 1 3.2 Milestone 2
  4. Code
  5. Unit Tests
  6. Applied Technologies
  7. Useful Links

1. Preamble

Markdown is a lightweight markup language widely used among developers. It is employed on numerous platforms that handle plain text (GitHub, forums, blogs, etc.), and Markdown files are commonly found in various repositories.

These Markdown files often contain links that are sometimes broken or no longer valid, negatively impacting the value of the shared information.

2. Project Summary

MD-Links is a project created in Node.js. It involves developing a library within this execution environment that reads and analyzes files in Markdown format. The goal is to verify the links contained in these files and report some statistics.

3. Project Development

The library creation was divided into Milestones—only two were completed for this specific case—each with different learning objectives. The project started with a flowchart outlining the steps to follow for Milestones 1 and 2, illustrating the functionality of our library.

Md-Links-chartflow

To enhance project performance, GitHub was used as a time management and planning tool through a Project, with two Milestones (one for each milestone) containing various issues.

projects-github

issues-github

3.1 Milestone 1

In this initial phase, the following tasks were completed:

  • Create the mdLinks promise.
  • Transform the input path to absolute.
  • Verify that the path exists in the system.
  • Confirm that the file is of type Markdown.
  • Read the file content using the readMkdwnFile function.
  • Identify the links within the document using isMdwnExtension.
  • Extract the links into an array using extractMarkdownLinks.
  • Create tests for each function in this milestone.

3.2 Milestone 2

The second stage of the project includes a single function and its test:

  • Generate the function to validate the links using validateLinks.
  • Implement tests for the function using mocks for Axios.

4. Code

The project's code is based on the modularization (CommonJS) of functions, aiding in organizing and structuring code in separate JS files. There are three main sections defining the functionality of our library:

lib: Contains files such as mdlinks.js, readFile.js, verifyExtension.js, extractfile.js, and validatelinks.js, housing the functions that bring the project to life.

test: Here, tests for both milestones are located.

index.js: Receives all information from the mdLinks function and returns a promise. Upon successful resolution, the information is displayed; otherwise, it is rejected.

It's worth noting the use of the Axios JavaScript library, utilized for making HTTP requests from Node.js, implemented in the validation function of Milestone 2.

4.1 Functions

As mentioned earlier, each task in our project is assigned a function. The functions are detailed below:

  1. In the mdlinks.js file, the mdLinks promise is created, serving to perform asynchronous operations in a controlled manner and manage the program's execution flow. Other functions related to file reading, extension verification, Markdown link extraction, and validation are executed here.

  2. In readFile.js, the readMkdwnFile function resides, returning a new promise with the fs.readfile method, providing an array with the contents of the Markdown file or an error if no content exists.

  3. The isMdwnExtension function verifies if a file has an extension corresponding to a Markdown file. It defines an array containing a list of Markdown file extensions, then checks if the extension of the provided path parameter matches these extensions, returning true if it does and false otherwise.

  4. extractMarkdownLinks uses a regular expression to find matches in the Markdown file, employing a while loop to execute the regular expression and extract each found link. After extracting these links, it saves them in an object with keys text, href, and file. Finally, this function returns a new array of objects with corresponding keys and values.

Once the aforementioned array is created, it is passed to Milestone 2, where only one function is needed:

  1. validateLinks receives an array of objects and validates their status for each link using the Axios library, allowing for HTTP requests from JavaScript. This function returns an array of promises to wait for all requests to complete before returning the results. It verifies the status of each HTTP link in an array of objects and updates each link with its respective status information.

In general, these functions provide utilities for working with files, validating links, and obtaining the status of URLs.

5. Testing

Our project also includes a set of tests (written by myself) for the functions readMkdwnFile, isMdwnExtension, extractMarkdownLinks, and validateLinks.

These tests also helped detect some Eslint errors, and as seen in the following image, the coverage reached almost 100% in all aspects.

Coverage test-coverage-mdlinks

6. Technologies Used

  • JavaScript: Implements functionality to analyze entered text and display results.
  • Node.js: A server-side JavaScript execution environment.
  • CommonJS: Modules are used to organize and structure code in separate JS files. module.exports is used to export functions and variables from the module, and require('./module') is used to import the module into another file.
  • fs Module: Interacts with the file system.
  • path Module: Works with file and directory paths.
  • Axios: Library for making HTTP requests.
  • EsLint: Linting tool for JavaScript.
  • Jest: Testing framework for JavaScript.

7. Useful Links

Promesas – JavaScript hecho fácil

Arrays, map, forEach, reduce y mucho más!

Así funcionan las Promesas y async/await en JavaScript

Node.js v6.17.1 Documentation

Node.js v21.2.0 documentation

Promise

How to Write a JavaScript Promise

Tests de código asíncrono

Introducción al testing desde cero con Jest

Aprende cómo aplicar Jest Mock paso a paso fácil y sin dolor

Cómo crear pruebas unitarias con JEST

md-links's People

Contributors

alexaolalde avatar genesismauries avatar

md-links's Issues

Comprueba que la ruta existe en la computadora

Una vez que tienes la ruta absoluta, asegúrate que la ruta exista en la computadora. Este paso es importante, ya que si la ruta ingresada es errónea la función mdLinks() deberá rechazarse con un error.

Lee un archivo

Ahora que sabes que el archivo es del tipo Markdown, lee este archivo y retorna su contenido. Para ver este contenido puedes utilizar un console.log() al momento de ejecutar la función.

El módulo fs (FileSystem) te será de utilidad. Como mencionamos en las consideraciones técnicas, preferimos que uses readFile (en lugar de readFileSync) y recomendamos el módulo fs/promises para utilizar estas funciones con promesas.

Hacer los tests unitarios

Los tests unitarios son una excelente forma de verificar si tus funciones están funcionando correctamente mientras escribes el código. En este proyecto, recuerda que no hay una interfaz gráfica de navegador, por lo tanto para poderlo probar es necesario recurrir a los test unitarios.

Recuerda que es muy importante testear tus funciones puras, mientras escribes la función mdLinks. También deberás testearla al final asegurándote que resuelva un arreglo con la información esperada.

Encuentra los links dentro del documento

Una vez tienes acceso al contenido del archivo, extrae los links que encuentres dentro del mismo. Estos links los tendrás que armar dentro de un arreglo para que la función de mdLinks los pueda resolver.

Asegúrate que el archivo es Markdown

Como la ruta que se utilizará para este hito, será la ruta de un archivo en específico, aventúrate a conocer cuál es su extensión.

Recuerda, las extensiones son esas letras al final del nombre de un archivo, por ejemplo: .js, .txt, .doc, etc.

Aquí podrá ser útil el módulo path.

Ten en cuenta que un archivo es considerado Markdown si tiene cualquiera de las siguientes extensiones: .md, .mkd, .mdwn, .mdown, .mdtxt, .mdtext, .markdown, .text; así que en caso de que la extensión del archivo no sea alguna de las anteriores, la promesa de la función mdLinks debería rechazarse con un error.

Transformar la ruta ingresada a absoluta

Los módulos de Node.js que utilizarás después, trabajan con rutas absolutas. Entonces, si a la función mdlinks(), se le pasa una ruta relativa, debes convertirla a absoluta primero. Puedes valerte del módulo path, con su método resolve().

Crear una Promise

El valor de retorno de nuestra librería es una Promesa que resuelve un array. Prueba leyendo sobre las promesas y creando una por tu cuenta utilizando new Promise()

Es importante que sepas qué es un callback pues las promesas los utilizarán.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.