简体   繁体   中英

Node.js Asynchronous read and write

I am having problem with asynchronous file read and write operations. only the last file is written to the server. js:

function uploadassignment(req, res){
    var path;
    var multiparty = require("multiparty");
    var form = new multiparty.Form();
    console.log(req.query);
    var filelength = req.query.filecount;
    console.log(filelength);
    form.parse(req, function(err, fields, files){
    console.log(req.body);
        for(i=0;i<filelength;i++){
            var img = files.file[i]; 
            console.log(img);
            console.log('divide');
            var fs = require('fs');
            fs.readFile(img.path, function(err, data){
                var originalfile = img.originalFilename.split('.');
                console.log(originalfile);
                var file_ext = originalfile[1];
                path = "public/assignments/"+img.originalFilename;
                console.log(path);
                fs.writeFile(path, data, function(error){
                    if(error)console.log(error);
                });
            })
        }
    });
};

This is a common bug caused by using a loop variable without a closure. By the time the callback for the read operation is invoked, the loop has terminated and the index i points to the last element (and hence your img contains the last file). Create a function (a closure) that accepts the index as the parameter and call this function from the loop:

function blah(i) {
        var img = files.file[i]; 
        console.log(img);
        console.log('divide');
        var fs = require('fs');
        fs.readFile(img.path, function(err, data){
            var originalfile = img.originalFilename.split('.');
            console.log(originalfile);
            var file_ext = originalfile[1];
            path = "public/assignments/"+img.originalFilename;
            console.log(path);
            fs.writeFile(path, data, function(error){
                if(error)console.log(error);
            });
        })
}
for(i=0;i<filelength;i++) blah(i);

This isn't quite an answer, but it is too long for a comment. What is not working? The file reading/writing bit of your code works fine:

var fs = require("fs")

img = {
    path: "./test.txt",
    originalFilename: "test.txt"
}

fs.readFile(img.path, function(err, data){
    if(err)console.log(err);
    var originalfile = img.originalFilename.split('.');
    console.log(originalfile);
    var file_ext = originalfile[1];
    path = "public/assignments/"+img.originalFilename;
    console.log(path);
    fs.writeFile(path, data, function(error){
        if(error)console.log(error);
    });
})

With a directory structure like:

script.js
text.txt
public
    assignments

I think your problem might be that you are assigning "fs" locally, then trying to call it from an async function. That might be why only the last one works (maybe.) Try moving var fs = require('fs'); to the top of your code.

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