React File Manager를 만들어 봅시다. Chapter XVII: Create Nodes List
15399 단어 typescriptexpressjavascriptmongez
이제 노드 파일과 디렉토리를 나열했지만 각 자식을 적절한 노드로 만들어야 합니다.
React 프로젝트에서 수행한 것과 동일한
Node 유형을 가져오고 가져옵니다.// src/utils/node.ts
// 👇🏻 import the Node type from the client directory xD
import { Node } from "./../../../client/src/apps/front-office/file-manager/Kernel/Kernel.types";
export type { Node };
/**
* Generate a node object to the given path,
* the given path should be relative to the data directory
*/
export default function makeNode(path: string, children: string[]): Node {
}
이제 클라이언트 디렉터리에서 동일한 노드 유형을 가져왔으므로 서버에서 사용할 수 있습니다.
그런 다음 새 노드 개체를 생성하는
makeNode 함수를 만들었습니다.// src/utils/node.ts
// 👇🏻 import the Node type from the client directory xD
import { Node } from "./../../../client/src/apps/front-office/file-manager/Kernel/Kernel.types";
import { isDirectory, size } from "@mongez/fs";
import { dataPath } from "./paths";
export type { Node };
/**
* Generate a node object to the given path,
* the given path should be relative to the data directory
*/
export default function makeNode(path: string, children?: string[]): Node {
// get the full path of the node
const fullPath = dataPath(path);
const node: Node = {
path,
name: path.split("/")?.pop() || "/",
isDirectory: isDirectory(fullPath),
size: size(fullPath),
};
if (node.isDirectory && children?.length) {
node.children = children.map((child) =>
makeNode((path === "/" ? path : path + "/") + child)
);
}
return node;
따라서 경로는
data 디렉토리에 대한 상대 경로가 되므로 루트인 경우 path는/가 됩니다.이름은 경로의 마지막 세그먼트이므로
/로 경로를 분할하고 마지막 세그먼트를 가져옵니다.주어진 자식은 노드의 자식 목록이므로 이를 매핑하고 각 자식에 대한 새 노드를 생성합니다.
자식이 있으면 루프를 돌고 각 자식에 대한 새 노드를 생성합니다.
Don't forget the given children is list of names for the given node path, so we need to add the child name to the path.
isDirectory는 isDirectory 패키지에서 가져온 @mongez/fs 함수의 결과입니다. 노드 경로의 전체 경로를 전달해야 하므로 fullPath를 사용하여 전체 경로를 가져오기 위해 dataPath를 사용했습니다.size는 size 패키지에서 가져온 @mongez/fs 함수의 결과입니다. 노드 경로의 전체 경로를 전달해야 하므로 fullPath를 사용하여 전체 경로를 가져오기 위해 dataPath를 사용했습니다.함수 호출
이제
listDirectory 경로로 이동하여 makeNode 함수를 호출해 보겠습니다.import fs from "@mongez/fs";
import makeNode from "app/utils/node";
import { dataPath } from "app/utils/paths";
import { Request, Response } from "express";
/**
*List directories
*/
export default async function listDirectory(
request: Request,
response: Response
) {
// get the directory path from the request query string
// let's set `/` as the default path
const path = (request.query.path as string) || "/";
const directoryPath = dataPath(path); // the full path to the directory
if (!fs.isDirectory(directoryPath)) {
return response.status(404).json({
message: "Directory not found",
});
}
// get the directory content
const children = fs.list(directoryPath);
return response.json({
node: makeNode(path, children),
});
}
이제 서버를 실행해서 다시 봅시다.

왈라, 작동합니다!.
실제로 노드가 배열이면 항상 빈 배열로 자식을 반환할 수 있습니다. 나중에 자식의 깊이를 설정하는 다른 기능을 추가하여 자식의 자식을 반환할 수 있기 때문입니다.
// src/utils/node.ts
/**
* Generate a node object to the given path,
* the given path should be relative to the data directory
*/
export default function makeNode(path: string, children?: string[]): Node {
// get the full path of the node
const fullPath = dataPath(path);
const node: Node = {
path,
name: path.split("/")?.pop() || "/",
isDirectory: isDirectory(fullPath),
size: size(fullPath),
};
// 👇🏻 we can always return children with empty array if the node is a directory
if (node.isDirectory) {
node.children = (children || []).map((child) =>
// 👇🏻 we need to check if the path is the root then we will just append it to the child
// if its not the root then we need to append `/` to the path and then append the child
makeNode((path === "/" ? path : path + "/") + child)
);
}
return node;
}
이제 모든 경로를 시도하여 제대로 작동하는지 확인할 수 있습니다.
http://localhost:3000/file-manager?path=/는 루트 디렉토리를 반환합니다. http://localhost:3000/file-manager?path=/Application는 Application 디렉토리를 반환합니다. 다음 장
다음 장에서는 이 API를 React 프로젝트에 구현하여 보다 현실적으로 만들 것입니다.
기사 저장소
Github Repository에서 챕터 파일을 볼 수 있습니다.
Don't forget the
mainbranch has the latest updated code.
지금 어디 있는지 말해줘
이 시리즈를 저와 함께 후속 조치하는 경우 현재 위치와 어려움을 겪고 있는 부분을 알려주시면 최대한 도와드리겠습니다.
살람.
Reference
이 문제에 관하여(React File Manager를 만들어 봅시다. Chapter XVII: Create Nodes List), 우리는 이곳에서 더 많은 자료를 발견하고 링크를 클릭하여 보았다 https://dev.to/hassanzohdy/lets-create-a-react-file-manager-chapter-xvii-create-nodes-list-4h82텍스트를 자유롭게 공유하거나 복사할 수 있습니다.하지만 이 문서의 URL은 참조 URL로 남겨 두십시오.
우수한 개발자 콘텐츠 발견에 전념
(Collection and Share based on the CC Protocol.)