Skip to content

节点文件结构(Node file structure)#

遵循节点结构中的最佳实践和标准可以使你的节点更易于维护。如果其他人需要使用这段代码,这会很有帮助。

🌐 Following best practices and standards in your node structure makes your node easier to maintain. It's helpful if other people need to work with the code.

节点的文件和目录结构取决于:

🌐 The file and directory structure of your node depends on:

  • 你的节点复杂度。
  • 是否启用节点版本控制。
  • npm 包中包含多少个节点?

n8n 建议使用 n8n-node 工具 来创建预期的节点文件结构。您可以根据需要自定义生成的脚手架,以满足更复杂的需求。

🌐 n8n recommends using the n8n-node tool to create the expected node file structure. You can customize the generated scaffolding as required to meet more complex needs.

必填文件和目录(Required files and directories)#

你的节点必须包含:

🌐 Your node must include:

  • 项目根目录下的 package.json 文件。每个 npm 模块都需要它。
  • 一个 nodes 目录,包含你的节点代码:
    • 此目录必须包含 base file,格式为 <node-name>.node.ts。例如,MyNode.node.ts
    • n8n 建议包含一个 codex 文件,其中包含节点的元数据。codex 文件名必须与节点的基础文件名相匹配。例如,给定一个名为 MyNode.node.ts 的节点基础文件,其 codex 名称为 MyNode.node.json
    • nodes 目录可以包含其他文件和子目录,包括用于版本的目录,以及分散在多个文件中的节点代码,以创建模块化结构。
  • credentials 目录,包含你的凭证代码。此代码存放在一个单独的 凭证文件 中。文件名格式为 <node-name>.credentials.ts。例如,MyNode.credentials.ts

模块化结构(Modular structure)#

You can choose whether to place all your node's functionality in one file, or split it out into a base file and other modules, which the base file then imports. Unless your node is very simple, it's a best practice to split it out.

一个基本的模式是将操作分离开。有关此的示例,请参考 HttpBin 入门节点

🌐 A basic pattern is to separate out operations. Refer to the HttpBin starter node for an example of this.

对于更复杂的节点,n8n 建议使用目录结构。可参考 Airtable 节点Microsoft Outlook 节点 作为示例。

🌐 For more complex nodes, n8n recommends a directory structure. Refer to the Airtable node or Microsoft Outlook node as examples.

  • actions:一个包含表示资源的子目录的目录。
    • 每个子目录应包含两种类型的文件:
    • 一个包含资源描述的索引文件(名称为 <resourceName>.resource.tsindex.ts
    • 用于操作 <operationName>.operation.ts 的文件。这些文件应有两个导出:操作的 description 和一个 execute 函数。
  • methods:一个可选的目录动态参数功能。
  • transport:一个包含通信实现的目录。

版本控制(Versioning)#

如果你的节点有多个版本,并且你正在使用完整版本控制,这会使文件结构更加复杂。你需要为每个版本创建一个目录,并且需要一个设置默认版本的基础文件。有关处理版本的更多信息,包括版本类型,请参阅 节点版本控制

🌐 If your node has more than one version, and you're using full versioning, this makes the file structure more complex. You need a directory for each version, along with a base file that sets the default version. Refer to Node versioning for more information on working with versions, including types of versioning.

决定数量要包含在包中的节点(Decide how many nodes to include in a package)#

构建节点时有两种可能的设置:

🌐 There are two possible setups when building a node:

  • 一个节点位于一个 npm 包中。
  • 单个 npm 包中包含多个节点。

n8n 支持这两种方法。如果你包含多个节点,每个节点应该在 nodes 目录中有自己的目录。

🌐 n8n supports both approaches. If you include more than one node, each node should have its own directory in the nodes directory.

程序化节点的最佳实践示例(A best-practice example for programmatic nodes)#

n8n 内置的 Airtable 节点 实现了模块化结构和版本控制,遵循推荐的模式。

🌐 n8n's built-in Airtable node implements a modular structure and versioning, following recommended patterns.