Moonglade

Modern Markdown blogging with AI-powered localization and search.

Tag: study

RSS

Using `readFile` as an example, how to implement it in Node.js

This article provides an in-depth analysis of the underlying implementation mechanisms of file reading operations in Node.js, with a focus on tracing the call chains of `fs.readFileSync` and `fs.readFile`. It points out that, whether synchronous or asynchronous, all operations ultimately converge on libuv's `uv_fs_read` function, with the execution mode distinguished by the presence or absence of a callback function. At the code level, it details how `FSReqCallback` and its base class `FSReqBase` encapsulate request state after entering the C++ layer from the JS layer, and how tasks are dispatched to the event loop through the `AsyncCall` and `Dispatch` mechanisms. For the asynchronous flow, it emphasizes how the `ReqWrap` template class adapts to the libuv interface, and how the `AfterInteger` callback function triggers the Promise's Resolve logic to return the result upon completion of the operation. Additionally, the article analyzes the details of permission checks and file descriptor management within the `open` function, revealing Node.js's meticulous considerations for platform compatibility and resource management at each level of abstraction. Finally, it summarizes legacy issues such as built-in module loading and asynchronous construction, aiming to help readers gain a deep understanding of Node.js's core architecture and design philosophy.

Views 185
2025 c++ daily javascript libuv nodejs source-code study v8

v8 build for Linux platform

This article documents the complete process of compiling V8 source code in an Ubuntu 24.04 environment and resolving linking issues. The author aims to obtain the V8 static library to research C++ and JS interoperation. However, the official documentation lacks explanations of the implicit relationships between build parameters, leading to two major challenges: first, the default linker reports an "unknown architecture" error; second, V8's custom C++ standard library results in undefined symbols. After extensive trial and error, it was found that using the lld linker resolves the architecture compatibility issue. Furthermore, setting `is_clang` to `false` and `use_custom_libcxx` to `false` in `args.gn`, combined with `v8_monolithic=true`, ultimately resulted in the successful generation of a static library that links and debugs correctly. The article reflects on the insufficient guidance in V8's official documentation regarding critical build configurations and suggests that maintainers improve parameter documentation to reduce developers' trial-and-error costs, ensuring that documentation serves as a guide rather than an obstacle.

Views 288
2025 c++ daily linux study v8

Post-Mortem After a Drinking Session

This article is a profound reflection on the act of drinking alcohol, aimed at eliminating future violations of precepts through introspection. Based on the Buddhist principle of the Four Right Efforts, the author points out that although drinking is a minor precept (a restriction rather than a fundamental prohibition), it should be completely avoided to ensure absolute safety. The text details the experience of breaking the precept during the New Year period due to friends' forceful invitations and pressure to drink, and deeply analyzes the harms of such social scenarios: not only does it violate the precepts, but true friendship is not sustained by alcohol and meat; rather, the secular habits commonly accepted by the group often conflict with the goals of spiritual practice. The author emphasizes that when facing pressure from others, one must steadfastly adhere to the Dharma-based decision, without compromising or settling for a lesser standard due to the lack of a suitable environment or the persuasion of others—just as one should not compromise by eating the "Three Pure Meats" when vegetarian options are unavailable. This lesson can be extended to all unwholesome practices, reminding practitioners to maintain sharp awareness in daily life, hold firmly to the precepts, and let the Dharma guide their actions, thereby ensuring that wholesome qualities already present grow stronger and new wholesome qualities arise, thus truly fulfilling the goal of abandoning evil and cultivating goodness in practice.

Views 267
alcohol buddhist-precepts daily four-right-efforts foxue interpersonal-relationships mindfulness reflections study

Mongoose Type Issue

This article discusses the TypeScript type definition deficiencies encountered when performing database refactoring with Mongoose in a NestJS environment. The author points out that whether using `typegoose` or `nestjs/mongoose`, the type system fails to provide effective field constraints and error messages when constructing query filters (`FilterQuery`). Specifically, even if a filter object is assigned properties that do not exist in the Schema, TypeScript does not report an error. This prevents the detection of spelling mistakes or logical errors during the compilation phase, which contradicts the original intent of TypeScript to reduce coding mistakes through strong typing. Given that this issue stems from Mongoose's own type definition mechanism and that TypeORM has poor support for MongoDB, the author ultimately decided to abandon the existing solution and chose to rewrite the Schema and related code to migrate to Prima. This prioritizes type safety and clarity for the development experience, reflecting a focus on the quality of type support when selecting an ORM.

Views 110
2024 mongoose orm study typescript work

Yinming Ruzhenglun: A Structured Overview of the Argumentation Theory

This passage is excerpted from the section on Hetuvidyā (Buddhist Logic) in Maitreya Bodhisattva's *Mahāyānasaṃgraha* (Treatise on the Ground of the Master). It systematically elaborates on the seven core elements of Buddhist logical debate. First, it defines the nature of debate (*vāda*), categorizing discourse into six types: ordinary speech (*vākya*), deliberation (*parīkṣā*), quarrel (*vāda*), defamation (*vāda*), right discourse (*sādhak*), and instruction (*upadeśa*). It emphasizes that the latter two are genuine and lead to benefit and profit, and thus should be cultivated, while the others require careful distinction or avoidance. Second, it details the place of debate and its basis. The basis of debate includes two types of established meanings—essential nature (*svabhāva*) and difference (*viśeṣa*)—as well as eight methods of establishment: thesis (*pratijñā*), reason (*hetu*), example (*udāharaṇa*), similarity (*sādṛśya*), dissimilarity (*asādṛśya*), direct perception (*pratyakṣa*), inference (*anumāna*), and authoritative testimony (*āgama*). It provides an in-depth analysis of the three criteria for direct perception: not non-apparent, not already considered but needing consideration, and not a deluded state. It also examines the five classifications of inference: characteristic, entity, function, dharma, and cause-and-effect. Furthermore, it outlines the three verifications of authoritative testimony: not contradicting the words of the sages, capable of eliminating defilements, and not violating the characteristics of dharmas. Third, the article proposes the five virtues of adornment in debate: mastery of one's own and others' positions, completeness of speech, fearlessness, propriety, and reverence. It lists twenty-seven types of praiseworthy merit obtained through these virtues. Simultaneously, it warns of the three states of defeat in debate: abandonment of speech, being refuted by speech, and excessive speech. It points out that if a debater commits any of these nine faults or thirteen types of regression, they fall into the state of defeat. Finally, it clarifies the three observations for exiting debate, requiring the debater to examine gain and loss, the timing and audience, and their own skillfulness before establishing a thesis. It summarizes the extensive functions of debate as mastery of one's own and others' positions, courageous fearlessness, and inexhaustible eloquence, aiming to achieve the manifestation of truth and the liberation of wisdom through rigorous logic and pure motivation.

Views 153
2024 debate logic study weishi zhongzhe

Lite Version MongoDB Full-Text Search

This article primarily explores technical solutions for implementing Chinese full-text search in the MongoDB Community Edition. Since the Community Edition does not natively support Chinese word segmentation engines, the author proposes a custom solution based on NestJS, Mongoose, and the `@node-rs/jieba` segmentation library. The article details the use of Docker to deploy a MongoDB environment with replica set support, ensuring service stability through a health check mechanism. In terms of architecture, the project is organized using a Monorepo pattern. By listening to database change events, Chinese text is automatically segmented and written back to the collection upon data insertion, thereby constructing a full-text index that supports Chinese retrieval. This solution not only implements basic query functionality but also covers multi-entity detection, value object handling, and a comparative analysis with Elasticsearch, providing developers with a complete technical practice reference for achieving efficient Chinese search at low cost in constrained environments.

Views 175
docker fulltext mongodb nest node search study work

OpenAPI client generation

This article documents the selection process and practical experience of automatically generating SDKs based on OpenAPI metadata. The author compared three libraries: `autorest`, `swagger-codegen-cli`, and `@hey-api/openapi-ts`, ultimately choosing the latter due to its superior performance in frontend environment compatibility, code conciseness, and type reuse. This choice effectively reduces the workload of manually writing request code and improves development efficiency. Using a NestJS backend and Vue frontend as examples, the article details the complete technical pipeline: configuring `nest-cli.json` to extract DTO and Entity types, utilizing a GitHub Actions pipeline to start the service in a CI environment to retrieve metadata, invoking `@hey-api/openapi-ts` to generate the SDK, and pushing it to a separate sub-repository. The frontend wraps the `@hey-api/client-fetch` client to implement unified authentication interception and error handling, directly importing the generated types and functions within Pinia Stores to achieve type safety and code reuse. This workflow not only reduces the collaboration cost between frontend and backend teams but also minimizes format errors through standardized interface definitions. Although the currently auto-generated parameter validation feature has limitations, the overall solution offers significant advantages in terms of type safety and development efficiency.

Views 385
2024 ci-cd github openapi study swagger vue work

ts strict mode configuration, comfortable

This article primarily demonstrates the TypeScript compiler options configured in strict mode and highlights their positive impact on the development experience. The core configuration includes setting the module system to NodeNext, targeting ES2021 as the compilation target, and enabling strict mode to catch more potential errors. Additionally, to support modern frontend framework features, the configuration enables experimental decorators and decorator metadata emission, and generates declaration files and source maps for debugging purposes. Notably, to reduce type error friction during initialization, the configuration specifically disables strictPropertyInitialization, allowing properties to be initialized later in the constructor. The author concludes by expressing appreciation for the comfort brought by strict mode, indicating that through reasonable compiler option configuration, developers can enjoy the safety and maintainability of strict type checking while balancing development efficiency by fine-tuning certain rules, thereby achieving a smoother coding experience.

Views 185
config daily study ts typescript typescript compiler

pyenv Notes

This article documents the practice and experience of managing Python versions using `pyenv` in an Ubuntu 24.04 environment. The motivation was that while building the MongoDB source code, the official documentation required Python 3.10+, but the system's default version 3.12.3 caused the build to fail due to API incompatibility. Since modifying the source code was not an option, the decision was made to use `pyenv` to specifically install a 3.10.x version. The article details the process of automatically installing `pyenv` via a `curl` script and configuring `~/.bashrc`. It also highlights the extremely unfriendly user experience of `pyenv`, specifically noting the lack of progress indicators, minimal information feedback, and the absence of interactive options during installation and build processes. Additionally, addressing the issue where `pip` and `poetry` command-line mirror source configurations failed, the author successfully configured the Tsinghua University or Tencent Cloud mirror addresses to accelerate dependency package downloads by manually creating and editing the `~/.pip/pip.conf` and `~/.config/pypoetry/config.toml` files. The article emphasizes the importance of not arbitrarily modifying the system's pre-installed Python environment and repeatedly warns developers to avoid writing programs that lack user feedback and interactivity. It suggests that readers refer to this configuration method in similar scenarios to avoid potential pitfalls.

Views 96
daily env install mongodb pyenv study

debug vue3 source code

This article introduces a simple solution for implementing source code debugging in Vue 3 projects. The core idea is to leverage the sourcemap files generated during the Vue 3 build process, combined with VS Code debugging configuration, allowing direct execution without modifying complex configurations. The article first demonstrates how to install dependencies using `pnpm` and run the development command, resulting in build artifacts in the `dist` directory that include map files. It then provides detailed `launch.json` configuration examples covering three debugging scenarios: first, Node.js debugging for the `npm run build` script; second, debugging remotely loaded Vue projects via URL, where it is important to set `webRoot`; and third, debugging original HTML files that reference local Vue packages, requiring correct configuration of `outFiles` to map source code paths. The article also lists complete environment setup steps, including cloning the Vue core repository, creating temporary HTML test files, and creating a Vue project using the official template. This solution aims to help developers quickly establish a debugging chain from browser breakpoints to Vue source code, improving development efficiency. Plans are in place to supplement this with a debugging video demonstration in the future.

Views 59
daily sourcemap study vue vue3 web