3

我想知道如何在 node.js 的 c++ 插件(.cc)文件中创建文件并在其中附加数据?

我已经使用下面的代码来做同样的事情,但无法在我的 ubuntu 机器中找到文件“data.txt”(背后的原因可能是下面的代码不是创建文件的正确方法,但奇怪的是我没有收到任何错误/编译时警告)。

FILE * pFileTXT;

pFileTXT = fopen ("data.txt","a+");

const char * c = localReq->strResponse.c_str();

fprintf(pFileTXT,c);

fclose (pFileTXT); 
4

1 回答 1

7

Node.js 依赖于libuv,这是一个 C 库来处理 I/O(异步与否)。这允许您使用事件循环。

你会对这本免费的在线书籍/libuv 简介感兴趣:http: //nikhilm.github.com/uvbook/index.html

具体来说,有一章专门介绍读/写文件

int main(int argc, char **argv) {
    // Open the file in write-only and execute the "on_open" callback when it's ready
    uv_fs_open(uv_default_loop(), &open_req, argv[1], O_WRONLY, 0, on_open);

    // Run the event loop.
    uv_run(uv_default_loop());
    return 0;
}

// on_open callback called when the file is opened
void on_open(uv_fs_t *req) {
    if (req->result != -1) {
        // Specify the on_write callback "on_write" as last argument
        uv_fs_write(uv_default_loop(), &write_req, 1, buffer, req->result, -1, on_write);
    }
    else {
        fprintf(stderr, "error opening file: %d\n", req->errorno);
    }
    // Don't forget to cleanup
    uv_fs_req_cleanup(req);
}

void on_write(uv_fs_t *req) {
    uv_fs_req_cleanup(req);
    if (req->result < 0) {
        fprintf(stderr, "Write error: %s\n", uv_strerror(uv_last_error(uv_default_loop())));
    }
    else {
        // Close the handle once you're done with it
        uv_fs_close(uv_default_loop(), &close_req, open_req.result, NULL);
    }
}

如果您想为 node.js 编写 C++,请花一些时间阅读这本书。这很值得。

于 2012-12-07T12:44:37.403 回答