I tried to use browserify with 'temp' and 'fs' modules, and all I got was this lousy error

I'm trying to migrate a node project to run in the browser. The project (nevermind the reason for the moment) writes to a temporary file, using temp with code similar to this:

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

temp.open('helloworld.txt', function (err, info) {
    if (err) {
        console.log('Failed to open a temp file:', err);
        return;
    }

    console.log('temp: ', info.path);
    fs.writeFile(info.path, 'Hello World!', function (err2) {
        if (err2) {
            console.log('Failed to write to a temp file:', err2);
            return;
        }
    });
});

When running the browserified code I get the following error:

Uncaught TypeError: undefined is not a function

for the following line:

fs.open(filePath, RDWR_EXCL, 0600, function(err, fd) {

which is called by temp.open.

I'm very much aware you cannot write files using plain ol' javascript in the browser, but I was wondering if browserify have some replacement for that, especially since we're talking about a temp file.

I found browserify-fs, and tried:

browserify -r fs:browserify-fs my-example.js -o bfied.js

but I get the exact same error. I tried to replace require('fs') with require('browserify-fs') but this resulted in a similar error as well (I of course installed browserify-fs module..)

Any suggested solution would be appreciated :) If this type of migration is not possible, I'd also be glad to know..

Thanks!

I stumbled across this post as I think I was trying to do pretty much the exact same thing as you. I am not sure where you got to with this, but I found that when using browserify-fs, you cannot access files outside the sandboxed state of the browser.

So when trying...

var fs = require('broserify-fs);
fs.read('hello.txt', 'utf8' ....

I got the same error as you, but when doing this...

fs.mkdir('/home', function() {
    fs.writeFile('/home/hello-world.txt', 'Hello world!\n', function() {
        fs.readFile('/home/hello-world.txt', 'utf-8', function(err, data) {
            console.log(data);
        });
    });
});

Everything worked fine (using just temporary files I think).

I am super new to this so I'm not sure what the best approach is. I imagine you either want to run a Node.js server locally and issue ajax commands to it to perform read/write operations, or investigate the HTML5 file system stuff - this looks like a good article - http://www.html5rocks.com/en/tutorials/file/dndfiles/

Hope that's some help (sorry you've had to wait 2 months for an answer ;) It was serendipitous I happened to stumble across your question and my heart sank when there were no answers)

Tom