Take the 2-minute tour ×

I want to know how i can create file and append data inside it in c++ addon (.cc) file of node.js ??

I have used below code to do same, but not able to find file "data.txt" in my ubuntu machine(reason behind it may be below code is not correct way to create file, but strange i haven't received any error/warning at compile time).

FILE * pFileTXT;

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

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


fclose (pFileTXT); 
share|improve this question
Please start using std::ofstream. –  Aleph Dec 7 '12 at 12:33

1 Answer 1

up vote 5 down vote accepted

Node.js relies on libuv, a C library to handle the I/O (asynchronous or not). This allows you to use the event loop.

You'd be interested in this free online book/introduction to libuv: http://nikhilm.github.com/uvbook/index.html

Specifically, there is a chapter dedicated to reading/writing files.

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

void on_write(uv_fs_t *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);

Spend some time reading the book if you want to write C++ for node.js. It's worth it.

share|improve this answer
Thanks a lot..!! I'll go through book and let you know, if stuck at any point..!! –  Mayur Dec 8 '12 at 9:57

Your Answer


