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?
JavaScript
x
36
36
1
var objHttp = require('http');
2
var objFS = require('fs');
3
4
objHttp.createServer(function(argClientRequest, argResult) {
5
objFS.readFile('z.html',
6
function(argError, argData) {
7
argResult.writeHead(200, {
8
'Content-Type': 'text/html'
9
});
10
argResult.write(argData);
11
argResult.end();
12
}
13
);
14
objFS.open('mynewfile1.txt', 'r', (argErr, argFD) => {
15
if (argErr) throw argErr;
16
17
objFS.readFile('mynewfile1.txt',
18
function(argError, argData) {
19
if (argError) throw argError;
20
21
argResult.writeHead(200, {
22
'Content-Type': 'text/html'
23
});
24
argResult.write(argData);
25
return argResult.end();
26
}
27
);
28
29
30
objFS.close(argFD, (argErr) => {
31
if (argErr) throw argErr;
32
33
});
34
});
35
}).listen(8080);
36
Advertisement
Answer
JavaScript
1
50
50
1
var objHttp = require('http');
2
var objFS = require('fs');
3
function firstReader(argResult){
4
5
return new Promise(function(resolve,reject){
6
objFS.readFile("z.html",
7
function(argError, argData) {
8
argResult.writeHead(200, {
9
'Content-Type': 'text/html'
10
});
11
argResult.write(argData);
12
13
}
14
);
15
})
16
17
}
18
function secondReader(argResult){
19
return new Promise(function(resolve,reject){
20
objFS.open('mynewfile1.txt', 'r', (argErr, argFD) => {
21
if (argErr) throw argErr;
22
23
objFS.readFile('mynewfile1.txt',
24
function(argError, argData) {
25
if (argError) reject();
26
27
argResult.writeHead(200, {
28
'Content-Type': 'text/html'
29
});
30
argResult.write(argData);
31
}
32
);
33
34
35
objFS.close(argFD, (argErr) => {
36
if (argErr) reject();
37
38
});
39
});
40
})
41
}
42
objHttp.createServer(function(argClientRequest, argResult) {
43
Promise.all([firstReader(argResult),secondReader(argResult)]).then(function(){
44
argResult.end();
45
}).catch(function(){
46
argResult.end();
47
})
48
49
}).listen(8080);
50