Question

I am attempting to check if a file exists in my mocha test. I know for a fact that the file exists in the test folder(I am placing it there for simplicity while I try and get this to work). But no matter what I do, fs.existsSync always fails. Logger.startup() creates the file. Logger.getFilename() returns a value like 5-17-30-2013.log. I am new to mocha so have no clue if I am making a classic blunder. As far as I know I am using mocha synchronously. Thanks for all of the help.

Here is my Mocha Test script:

var logger = require('../logger');
var fs = require('fs');

describe("Logger", function () {
    it("Creates a file", function () {
        logger.startup();
        console.log(logger.getFilename());
        if (!fs.existsSync(logger.getFilename())) {
            throw ("Logging File Does Not Exist");
        }
    })
})
Was it helpful?

Solution

The currently accepted self-answer's explanation falls short. It says:

Apearently fs looks at the root of the project, the package.json folder, and not realative to the file calling it, which I did not know.

Sure, but it's not happenstance or a quirk of the fs module. The fs module uses process.cwd() to interpret relative paths passed to it. Unless it is changed with process.chdir(), process.cwd() is the directory in which the current process has been started. Since mocha is usually launched from the root of a project, then in a mocha process, process.cwd() is usually going to be the root of the project. If mocha were launched from a different directory, then process.cwd() would have a different value.

The confusion may come from how the module system handles relative paths. A module name with a relative path will be interpreted relative to the __dirname of the current file. This may be a value different from process.cwd().

OTHER TIPS

try using process.cwd() to determine the working directory fs.exists is running from

I believe you are looking for __dirname, try to prepend it to the filename.

Documentation: http://nodejs.org/api/globals.html#globals_dirname

I followed @jjm and his advice on the program. After logging where it thought the file was, it turns out that it was looking in the folder "logger", not "logger/test" Apearently fs looks at the root of the project, the package.json folder, and not realative to the file calling it, which I did not know.

You can use fs.open(filepath, 'r', callback);

http://nodejs.org/api/fs.html#fs_fs_open_path_flags_mode_callback

This worked for me:

describe("Logger", function () {
    it("Creates a file", function (done) {
        logger.startup();
        console.log(logger.getFilename());
        fs.readFile(logger.getFilename(), done);
    });
});
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top