简体   繁体   中英

Node.js - Empty file written, but why?

TL;DR Why is the first file written, but the remaining files empty?

I have a for loop in Node.js that loops an array list of file strings. Each string represents a different file in it's respective directory. The array contains three values that are needed to create three seperate files. After the first file is created and written to, the second and third files are created but remain empty. Below is the short hand version of the code. Any help is much appreciated.

for(i in file_tree) {

  fp = fs.createWriteStream(file_tree[i]);

  for(i in data) {
    fp.write(data[i]+'\n', function (err) { if(error) throw err;});
  }

} // end for loop - file_tree

====== SOLUTION =====

file_tree = [
    pn+ '/theme/file1',
    pn+ '/theme/file2',
  pn+ '/theme/file3',
];

for(i in file_tree) {

    file_name = file_tree[i];
    fp = fs.createWriteStream(file_name);

    data = [];
    switch(file_name) {
        case pn+ "/theme/file1":
                    --- snip --
            break;

        //
        // ERROR BEGINS HERE : Notice no '/' prefix
        //
        case pn+ "theme/file2":
            --snip--
            break;

        default: show(help);
    }

    for(i in data) {
            fp.write(data[i]+'\n', function(err) { if (err) throw err; });
    }
}

data has not been properly initialized. The previous code was:

file_tree = [ pn+ '/theme/file1', pn+ '/theme/file2', pn+ '/theme/file3'];
for(i in file_tree) {
    file_name = file_tree[i];
    fp = fs.createWriteStream(file_name);
    data = [];
    switch(file_name) {
    case pn+ "/theme/file1":
        data.push("content-1");
        break;
    case pn+ "theme/file2": // <-- error
        data.push("content-2");
        break;
    default: show(help);
    }
    for(i in data) {
        fp.write(data[i]+'\n', function(err) { if (err) throw err; });
    }
} 

Since the case statement was missing a slash, it didn't match, and therefore, data was empty.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM