A
A
Alexander Koshelev2018-04-07 01:42:51
Node.js
Alexander Koshelev, 2018-04-07 01:42:51

Why doesn't it read the included file correctly in Node.js?

Good evening guys, who will tell you this moment?
Here is the code for the first file

var http = require("http");

http.createServer(function (req, res) {
  res.writeHead(200, {'Content-type': 'text/html; charset=utf-8'});
  res.end('подключился этот файл');
 
}).listen(7777);

in the second file, I include the first file and try to display the content of the first file
var http = require('http');
var fs = require('fs');

http.createServer(function(req,res){
  fs.readFile('1.js', 'utf8', function(err, data){
    res.writeHead(200, {'Content-type': 'text/plain'});
    if(err){
      res.write('couldn\'t read file');
    } else {
      res.write(data);
      }
    res.end();
  });
}).listen(7777, function(){console.log('bould to port 7777');});
console.log('server run');

but as a result, something strange for me is displayed on the screen in the browser
var http = "http";
http.createServer(function(request, response){
console.log("run server");


}).listen(9999)

Can anyone explain why this happened and how to read the content of the first file correctly?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Abigovor, 2018-04-08
@Xandr24

Try like this

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

http.createServer(function(req,res){

    var readStream = fs.createReadStream('1.js', 'utf8');

    readStream.on('open', function () {
      // This just pipes the read stream to the response object (which goes to the client)
      readStream.pipe(res);
    });

    
    readStream.on('error', function(err) {
      res.end(`couldn\'t read file`);
    });

})
.listen(3000, function() {console.log('bould to port 7777')} );

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question