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

如何通过stdin读取NodeJS传递给C++进程的文件?

问题

我编写了一个调用第三方库的C程序,该库的方法需要传入istream才能运行。我通过Node.js的child_process模块启动编译后的C程序,想通过stdin向C++进程传输文件,但不知道如何将传入的文件转换为istream。

尝试过的代码

C++代码

#include <iostream>
#include <chrono>
#include <string>
#include <CGAL/IO/read_STL.h>
// 需根据实际情况引入Mesh类型对应的头文件

using namespace std;
using namespace chrono;

int main(int argc, char **argv)
{
    cout << "\n---------------- STL TO PRIMITIVE ----------------\n" << endl;
    auto beg = high_resolution_clock::now();

    // 获取标准输入流
    std::istream &input_stream = std::cin;

    const double mv = 2;
    const double min_threshold = 0.1;
    const unsigned int depth = 7;
    string method = "threshold";
    Mesh mesh;

    // 读取STL文件
    cout << "~ Reading STL file..." << endl;
    if (!CGAL::IO::read_STL(input_stream, mesh))
    {
        cout << "ERROR WHILE READING THE FILE" << endl;
    }
    return 0;
}

Node.js代码

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

const fileContent = fs.readFileSync("./PipedPBase.stl");

const process = spawn('../MeshReshaper/build/release/MeshReshaper',{ stdio: ['pipe', 'inherit', 'inherit'] });

process.stdin.write(fileContent.toString());
process.stdin.end();

process.stderr.on('data', data => {
    console.log("ERROR -> " + data);
})

process.on('close', code => {
    console.log("Closed with code " + code);
});

问题原因及解决方法

你的C++端代码本身没问题——std::cin就是标准的istream对象,直接传给read_STL是正确的。失败的核心原因在Node.js端:STL是二进制文件,你用fileContent.toString()把二进制内容转成字符串,会破坏原始二进制结构,导致CGAL库无法解析。

修正后的Node.js代码

直接写入原始二进制Buffer,不要做字符串转换:

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

const fileContent = fs.readFileSync("./PipedPBase.stl");

// 避免和全局process重名,改为childProcess
const childProcess = spawn('../MeshReshaper/build/release/MeshReshaper',{ stdio: ['pipe', 'inherit', 'inherit'] });

// 直接写入二进制数据
childProcess.stdin.write(fileContent);
childProcess.stdin.end();

childProcess.stderr.on('data', data => {
    console.log("ERROR -> " + data.toString());
})

childProcess.on('close', code => {
    console.log("Closed with code " + code);
});

额外检查项

  1. C++端依赖:确保引入了Mesh类型对应的CGAL头文件,编译时链接了CGAL及相关依赖库(如-lCGAL -lgmp,需根据CGAL版本调整)。
  2. 错误输出优化:把C++端的错误信息输出到cerr,方便Node.js的stderr监听捕获:
if (!CGAL::IO::read_STL(input_stream, mesh))
{
    cerr << "ERROR WHILE READING THE FILE" << endl;
    return 1; // 返回非0错误码,方便Node端判断执行结果
}
  1. 路径验证:确认Node.js中STL文件路径、C++程序路径均为当前工作目录下的正确路径。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.26 03:02:49