You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

无法向Node.js子进程推送换行符:Terraria服务器命令执行问题

Node.js 操控Terraria服务器时命令无法触发的问题

我用Node.js编写代码启动并操控Terraria tModLoader服务器,但遇到了换行符无法触发命令执行的问题。

我的代码如下:

const { spawn } = require("child_process");

const server = spawn(
  "dotnet",
  [
    "tModLoader.dll",
    "-server",
    "-config",
    "serverconfig.txt",
    "-port",
    "7771",
    "-noupnp",
    "-ip",
    "172.23.85.11",
    "-world",
    "C:\\Users\\cringe\\Documents\\My Games\\Terraria\\tModLoader-1.4.3\\Worlds\\world.wld",
    "-pass",
    "",
  ],
  {
    stdio: "pipe",
    cwd: "C:\\Program Files (x86)\\Steam\\steamapps\\common\\tModLoader",
  }
);

server.on("error", (error) => console.log(error));
server.stdout.on("data", (data) => console.log(data.toString()));
server.stderr.on("data", (data) => console.log(data.toString()));
server.stdout.on("data", (data) => {
  if (data.toString().includes("exit")) {
    console.log("exiting server");
    server.stdin.write("exit\r\n", (error) => {
      if (error) console.log(error);
    });
  }
});

注:原代码中的Windows路径未转义,已修正为双反斜杠格式,避免解析错误。

我尝试过以下方法但均无效:

  • 调用stdin.write("exit\n")和stdin.write("exit\r"),无响应;
  • 为stdin.write("exit\n")搭配stdin.cork()和stdin.uncork(),仍无效果;
  • 调用stdin.end("exit"),命令被推送但服务器判定无效,推测是stdin.end()引入额外内容导致命令损坏。

解决办法

1. 先修正路径解析问题

Windows路径中的单个反斜杠\在JavaScript字符串中会被视为转义字符,导致实际传递给子进程的路径错误。必须将路径改为双反斜杠\\或正斜杠/:

// 示例:使用正斜杠
"-world", "C:/Users/cringe/Documents/My Games/Terraria/tModLoader-1.4.3/Worlds/world.wld",
cwd: "C:/Program Files (x86)/Steam/steamapps/common/tModLoader"

路径错误可能导致服务器启动异常,进而影响命令交互。

2. 确保使用正确的换行符并明确编码

Terraria服务器在Windows环境下通常以\r\n作为命令结束标记,写入时需明确指定编码为utf-8,确保命令被正确传递:

server.stdin.write("exit\r\n", "utf-8", (err) => {
  if (err) console.error("命令写入失败:", err);
});

3. 等待服务器就绪后再发送命令

原代码监听stdout中的"exit"字符串作为触发条件,但这并非服务器就绪的信号。需等待服务器输出命令就绪提示(如Type 'help' for a list of commands)后再发送命令:

server.stdout.on("data", (data) => {
  const output = data.toString();
  console.log(output);
  if (output.includes("Type 'help' for a list of commands")) {
    console.log("服务器就绪,发送exit命令");
    server.stdin.write("exit\r\n", "utf-8", (err) => {
      if (err) console.error(err);
    });
  }
});

4. 调整子进程的stdio配置

尝试修改spawn的stdio选项,开启shell模式(针对Windows环境):

{
  stdio: ["pipe", "pipe", "inherit"],
  cwd: "C:\\Program Files (x86)\\Steam\\steamapps\\common\\tModLoader",
  shell: true
}

开启shell: true可解决部分Windows下的子进程交互问题,但需注意安全风险。


内容的提问来源于stack exchange,提问作者Trumpas

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.16 00:11:04