Navigating the static folder in Deno: A guide to managing static assets

Is it possible to change the static resource file based on the URL query? Here is an example of my folder structure:

/root
-> server.ts
-> /projects
    -> libraries used in index.html files
    -> /project1
       -> index.html
       -> files used in index.html
    -> /project2
       -> index.html
       -> files used in index.html

This is how static files are handled in Deno using the Oak library:

app.use(async (ctx, next) => {    
    await send(ctx, ctx.request.url.pathname, {
        root: `${Deno.cwd()}/static`,
    })

    next()
});

The goal is to display the corresponding index.html file for a specific project ID when accessing a URL like mydomain.com/project/project1.

Currently, the Oak router is used to redirect URLs in this manner:

const router = new Router();
router.get('/project/:project_id', project)
export const project = async (ctx: RouterContext) => {
    ctx.render(`${Deno.cwd()}/projects/` + ctx.params.projectid + '/index.html');
}

Thank you for any assistance provided.

Answer №1

Is your question adequately answered?

For instance: The script dynamically looks for existing folders, and if not found, an error will be generated:

No such file or directory (os error 2)

.
├── projects
│   └── foo
│       └── index.html
└── server.ts
// ./server.ts

import { Application } from "https://deno.land/x/oak/mod.ts";

const app = new Application();

app.use(async (context) => {
    await context.send({
        root: Deno.cwd(),
        index: "index.html",
    });
});

await app.listen({ port: 8000 });
// ./projects/foo/index.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
</head>
<body>
    <h1>foo</h1>
</body>
</html>
deno run --allow-net --allow-read=. server.ts

# or /foo, /foo/index.html
curl localhost:8000/projects/foo/
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE-edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
</head>
<body>
    <h1>foo</h1>
</body>
</html>

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Creating organized lists in Angular 4 using list separators

I'm struggling to organize a list with dividers between categories to group items accordingly. Each divider should be labeled with the month name, and the items under it should correspond to that specific month. My Goal: - August - item 1 - item ...

How can I iterate through a variable in TypeScript?

initialize() { var elements = []; for (let i = 1; i <= 4; i++) { let node = { name: `Node ${i}` }; elements.push({ [`node${i}`]: node }); if (i < 4) { let edge = { source: `node${i}`, target: ...

Retrieve the JSON information specifically for the selected ID

Having a set of JSON data, with 2 base IDs and attachment data within each ID. The goal is to click on a base ID and display its attachment data on a separate page. How can I retrieve information for the clicked ID only? { "_embedded": { "deli ...

Angular 2 Login Component Featuring Customizable Templates

Currently, I have set up an AppModule with a variety of components, including the AppComponent which serves as the template component with the router-outlet directive. I am looking to create an AuthModule that includes its own template AuthComponent situa ...

I have a Visual Studio 2019 solution that consists of two projects - one is an Angular project and the other is written in TypeScript. I have successfully configured

We are currently utilizing Visual Studio 2019 (not the VS Code version) for our project. Within this solution, we have multiple projects included. One of these projects contains Angular code that we compile using the traditional 'ng build' comma ...

Learning to utilize the i18n library with React Vite

The developer console is showing the following message: i18next::translator: missingKey en translation suche suche Here is the file structure of my project: vite.config.ts i18n.js test/ src/ components/InputSearch.tsx routes/ public/ de/translation. ...

Retrieve the IDs of all children and grandchildren within a parent ID using Typescript

If I were to have an array of objects containing hierarchical data: const data = [ { groupId: 1, parentGroupId: null }, { groupId: 2, parentGroupId: 1 }, { groupId: 3, parentGroupId: 1 }, { groupId: 4, parentGroupId: null }, { groupId: 5, parentG ...

What seems to be the issue with my @typescript-eslint/member-ordering settings?

I am encountering an issue where my lint commands are failing right away with the error message shown below: Configuration for rule "@typescript-eslint/member-ordering" is throwing an error: The value ["signature","public-static-field","pro ...

The designated function name can be either "onButtonClick" or "onClickButton"

I am a Japanese developer working on web projects. Improving my English language skills is one of my goals. What would be the correct name for a function that indicates "when a button has been clicked"? Is it "onButtonClick"? Maybe "onClickButton"? Co ...

Utilizing a class member's data type

I need to inform Typescript that a member of my class is derived from another class. For instance: Class Main{ getDataFromChild(data){ console.log(data) } } Class Child{ getDataFromChild: Main.getDataFromChild } Scenario Application In my s ...

The issue of excessive recursion in Typescript

Currently, I am in the process of learning Typescript while working on some exercises. While attempting to solve a particular problem, I encountered an error related to excessive recursion. This issue arises even though I created wrapper functions. About ...

Collaborate and reuse Typescript code across various Node projects

Imagine we have a project structured like this: webapps ProjectA SomeClass.ts Package.json ProjectB SomeClass.ts Package.json Common LoggingClass.ts Package.json The Common "LoggingClass" needs to import a module from NPM. Let's say that ...

The comparison between importing TypeScript and ES2015 modules

I am currently facing an issue with TypeScript not recognizing the "default export" of react. Previously, in my JavaScript files, I used: import React from 'react'; import ReactDOM from 'react-dom'; However, in TypeScript, I found tha ...

Error: The function list.forEach does not exist within service.buildList [as project]

Today, I've been grappling with a challenging issue. As someone new to Typescript and Angular, I'm attempting to make a call to my backend API. However, when trying to populate an array for display, I keep encountering an error that says rawRegis ...

What causes type checks to be skipped when spreads are used on type-guarded types?

Query: Why doesn't a compile-time error occur when I overlook adding nested fields to an object of type T, while constructing the object using object spread? Illustration: interface User { userId: number; profile: { username: string } } f ...

The onClick event handler is functioning properly, but the ngOnInit() lifecycle method is not executing the function as

I have created a filter function that is applied to elements in a list. It works when I use it on the page with a click event, like this: <button (click)="FilterFn5()"> do </button> However, it does not work when I put the function i ...

Using HTTP POST to subscribe and implementing a try-catch block

When using Angular2's http.post, I encountered an issue where the headers were not sent to the CORS server. To address this, I attempted to create a loop that would retry the request until it succeeds. However, this resulted in an endless loop. How ca ...

How can I clear the div styling once the onDismiss handler has been triggered

Seeking assistance with resetting a div on a Modal after it has been closed. The issue I am facing with my pop-up is that the div retains the previous styling of display: none instead of reverting to display: flex. I have searched for a solution without su ...

Export interface for material-ui wrapper to cast any type in TypeScript (React)

I work with React using TypeScript. Recently, I encountered an issue with exporting. I'm creating an interface that encapsulates components from Material-ui. Here is a simplified example: Wrapping.tsx import { default as Component, ComponentProps ...

Retrieve information prior to CanActivation being invoked

As I develop a web application utilizing REST to retrieve data (using Spring Boot), the server employs cookies for authenticating logged-in users. Upon user signing in, I store their information in the AuthenticationHolderService service (located in root ...