Skip to content
Advertisement

How to read and open two different files in nodejs?

I have observed in this code that we can’t open the file after we have readFile.

The computer complains about Error [ERR_STREAM_WRITE_AFTER_END]: write after end

Of course if I remove the readFile function then this error goes away but I want to understand why this error is occurring even though I am using two different files for reading and opening.

What is the way to read and open two different files?

var objHttp = require('http');
var objFS = require('fs');

objHttp.createServer(function(argClientRequest, argResult) {
    objFS.readFile('z.html',
        function(argError, argData) {
            argResult.writeHead(200, {
                'Content-Type': 'text/html'
            });
            argResult.write(argData);
            argResult.end();
        }
    );
    objFS.open('mynewfile1.txt', 'r', (argErr, argFD) => {
        if (argErr) throw argErr;

        objFS.readFile('mynewfile1.txt',
            function(argError, argData) {
                if (argError) throw argError;

                argResult.writeHead(200, {
                    'Content-Type': 'text/html'
                });
                argResult.write(argData);
                return argResult.end();
            }
        );


        objFS.close(argFD, (argErr) => {
            if (argErr) throw argErr;

        });
    });
}).listen(8080);

Advertisement

Answer

var objHttp = require('http');
var objFS = require('fs');
function firstReader(argResult){

    return new Promise(function(resolve,reject){
        objFS.readFile("z.html",
        function(argError, argData) {
            argResult.writeHead(200, {
                'Content-Type': 'text/html'
            });
            argResult.write(argData);
         
        }
    );
    })
   
}
function secondReader(argResult){
    return new Promise(function(resolve,reject){
        objFS.open('mynewfile1.txt', 'r', (argErr, argFD) => {
            if (argErr) throw argErr;
    
            objFS.readFile('mynewfile1.txt',
                function(argError, argData) {
                    if (argError) reject();
    
                    argResult.writeHead(200, {
                        'Content-Type': 'text/html'
                    });
                    argResult.write(argData);
                }
            );
    
    
            objFS.close(argFD, (argErr) => {
                if (argErr) reject();
    
            });
        });
    })
}
objHttp.createServer(function(argClientRequest, argResult) {
   Promise.all([firstReader(argResult),secondReader(argResult)]).then(function(){
    argResult.end();
   }).catch(function(){
    argResult.end();
   })
   
}).listen(8080);
User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement