Node js beginner gets error message

this is my code for a simple node.js application:

var http = require('http');
var fs = require('fs');
var path = require('path');
var url = require('url');
var port = process.env.port || 1337;

http.createServer(function onRequest(req, res) {

var urlParts = url.parse(req.url);

var doc = '/docs' + urlParts.pathname;

path.exists(doc, function fileExists(exists) {

    if (exists) {

        res.writeHead(200, { 'Content-Type': 'text/plain' });
        fs.createReadStream(doc).pipe(res);

    } else {
        res.writeHead(404);
        res.end('Not Fouind\n');
    }
});
}).listen(port);

When I try to start it, I get an error message:

path.exists(doc, function fileExists(exists) {
                                    ^
                                  TypeError:Undefined is not a function

This is copied from a tutorial, so I'm not sure what is going on. (PS: I am using Visual Studio)

+4
source share
2 answers

I think that is path.existsout of date. I used to fs.exists. Try it.

+8
source
fs.exists(doc, function fileExists(exists) {

    if (exists) {

        res.writeHead(200, { 'Content-Type': 'text/plain' });
        fs.createReadStream(doc).pipe(res);

    } else {
        res.writeHead(404);
        res.end('Not Fouind\n');
    }
});

path.existsis not a function, a function exists in module fsc fs.exists.

+3
source

All Articles