Moonglade

Modern Markdown blogging with AI-powered localization and search.


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 186
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

Some Thoughts on Document Editing and Version Tracking

This article explores how to integrate Feishu Cloud Documents with Git version control to address the lack of fine-grained change tracking inherent in purely online documents during collaborative editing. The author points out that although Feishu supports version history, it lacks the critical feature of change descriptions, making it difficult to precisely locate historical versions during frequent revisions. In contrast, the Markdown format, due to its plain-text nature, is better suited for content-level version control via Git, effectively addressing needs such as content proofreading, multi-branch directory management, and low-cost web publishing. The article proposes a hybrid workflow: converting raw Word documents into unformatted Markdown and storing them in a Git repository as the source of truth for content version control; simultaneously importing the content into Feishu Cloud Documents for multi-user online commenting, discussion, and change approval. The Git branching mechanism allows for flexible management of different directory structures, while static site frameworks enable the easy conversion of Markdown into web pages or publication styles. This solution achieves a separation of content and formatting, ensuring both transparency and traceability in the revision process while meeting collaboration and publishing requirements across various scenarios. It serves as an effective strategy for handling complex document revision tasks.

Views 286
daily document-collaboration git markdown project-management static-site-generator version-control

NestJS pg template

This article introduces a backend project template based on NestJS, PostgreSQL, and TypeORM, aimed at providing a standardized development foundation. The article first outlines the configuration management approach, which involves reading YAML files and combining them with class-validator for strict data validation and transformation, ensuring the security and standardization of configurations. Next, it demonstrates how to use Docker Compose to quickly deploy Redis and PostgreSQL, optimizing the local development environment. The core functional modules include implementing database operations and migration management using TypeORM, as well as building a user authentication and permission control system based on JWT, Passport, and RBAC mechanisms, supporting dynamic retrieval of interface permission information via metadata. Additionally, the template integrates OpenAPI documentation generation and SDK automation tools to facilitate frontend integration. The logging system utilizes Winston and Dayjs to achieve Nest-style logging in development environments and file-based logging in production environments. Finally, the article covers specific data migration commands and a code submission process that follows the Conventional Commits specification, providing a complete technology stack reference for building robust, scalable enterprise-level backend applications.

Views 142
2024 daily nest node pgsql typeorm

Node.js backend Dockerfile example

This article introduces two Docker image build solutions based on Node.js, aiming to optimize image size and resolve environment dependency issues through layered build techniques. The first solution is designed for simple scenarios and adopts a three-stage build process: it first installs development dependencies, then executes build commands to generate artifacts, and finally integrates them into the production environment, striving to minimize the final image size. The second solution targets complex scenarios, focusing on resolving Linux graphics library dependencies required by the Canvas library, the Python runtime environment, and the installation of Chinese fonts. This solution configures domestic mirror sources to accelerate downloads and pre-installs Python and necessary system libraries in the production stage, ensuring the completeness and stability of the application runtime. Both solutions follow best practices by using multi-stage builds to isolate development, build, and production environments, effectively reducing redundant files in the final delivered image. Additionally, they ensure service availability through health check mechanisms, providing practical containerized deployment references for Node.js projects of varying complexity.

Views 144
ci-cd devops docker dockerfile fonts multistage-build node nodejs python web-service

GitLab Pipeline DingTalk Notification

This document describes how to integrate DingTalk bot notifications into a GitLab CI pipeline. The author created a base repository, `share/gitlab-ci`, which contains a `dingtalk.yml` template file. This file leverages GitLab Hook events to call the DingTalk API via `curl` to send messages. The core implementation includes defining global variables, validating the Access Token and URL-encoding the project address in the prepare stage, and constructing a Markdown message in the send stage that includes details such as task status, commit information, and the executor. It supports displaying different colors based on statuses like success or failure and includes jump buttons to view project and task details. In specific projects, this template is referenced using the `include` directive, and the `.dingtalk` configuration is inherited via `extends` in tasks across various stages, thereby enabling automated notifications for steps such as code inspection, building, and deployment. This solution addresses the previous issue where only repository information was recorded without pipeline notifications, achieving full-process visual feedback from task initiation to execution results. This enhances the transparency and collaboration efficiency of the DevOps workflow.

Views 341
ci-cd daily devops dingtalk integration gitlab gitlab ci

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

nginx Cipher Suite Security Audit

This article documents the company's entire process of identifying and resolving HTTPS cipher suite security vulnerabilities during the Level 3 Classified Protection (MLPS Level 3) assessment. Initially, scanning with the `nmap` tool revealed the presence of insecure cipher suites. Although the Nginx configuration was optimized to disable TLS 1.2 and retain only secure suites, external access tests still indicated issues. By comparing the results of local self-testing, which showed normal behavior, with the anomalies observed from external networks, it was determined that traffic passed through other middleware before reaching Nginx. After consulting with the operations team and reviewing historical purchase records, the root cause was finally identified as an incorrectly configured TLS restriction in the Alibaba Cloud WAF. Disabling the WAF caused the issue to disappear, and the problem was subsequently resolved completely through product upgrades and proper configuration. This experience not only highlighted the importance of configuring front-end middleware in security architectures but also prompted a deep reflection on troubleshooting methodologies: one should follow a logic of narrowing down from a broad scope to a specific one, using the discrepancies between internal and external network tests to quickly locate bottlenecks, thereby avoiding blind trial-and-error. Although inefficient communication with the operations team reduced efficiency during the process, the core lesson lies in establishing clear, progressive troubleshooting thinking, transforming theoretical insights into precise technical localization, and thus efficiently resolving security risks in complex network environments.

Views 200
2023 centos cloud docker nginx security 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