Node JS fs create new file module not running on localhost

Viewed 21

I'm trying to run a node js code with my visual studio ide but the index file is not running on local server its showing loading only

var fs = require('fs');
var http=require('http');
var server=http.createServer(function(req,res)
{
    if (req=='/')
    {
        fs.writeFile('mynewfile3.txt', 'New text', function (error) {
           if(error)
           {
            res.writeHead(200,{'Content-Type':'text/html'});
            res.write('file was not written');
            res.end();
           }
           else{
            res.writeHead(200,{'Content-Type':'text/html'});
            res.write('file was written');
            res.end();
           }
          });
    }
});

server.listen(7070);
console.log('server run');

This is my index.js file

I'm also attaching the package.json file

{
  "name": "write",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",

      "scripts": {

    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "keywords": [],
  "author": "",
  "license": "ISC"
}

Can anyone help me with this issue?

1 Answers

Sure! Short answer : if (req=='/') will always be false.

You might change that to something like if (req.url === '/') instead.

Related