Skip to content

Instantly share code, notes, and snippets.

@kaworu
Created March 19, 2014 10:45
Show Gist options
  • Save kaworu/9639298 to your computer and use it in GitHub Desktop.
Save kaworu/9639298 to your computer and use it in GitHub Desktop.
var fs = require("fs");
function read(path, callback) {
fs.readFile(path, 'utf8', callback);
}
function cat(path) {
read(path, function (err, data) {
if (err)
throw err;
console.log(data);
});
}
try {
cat(process.argv[2]);
} catch (e) {
console.err("some error was thrown: " + e.message);
}
@kaworu
Copy link
Author

kaworu commented Mar 19, 2014

% node cat.js /do-not-exist

/usr/home/alex/cat.js:10
            throw err;
                  ^
Error: ENOENT, open '/do-not-exist'

@whyhankee
Copy link

Asyncness problem, when you change the code to the code below you get your expected result.
Note: the fs.readFile_Sync_

I would suggest passing down the err to the caller (don't use a try-catch here)

var fs = require("fs");

function read(path, callback) {
    fs.readFileSync(path, 'utf8', callback);
}

function cat(path) {
    read(path, function (err, data) {
        if (err)
            throw err;
        console.log(data);
    });
}

try {
    cat(process.argv[2]);
} catch (e) {
    console.log("some error was thrown: " + e.message);
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment