Search code examples
angularjsnode.jsgulpbrowserify

Cannot find fs in controller


I'm a node newbie so forgive me if this is something simple..I searched the internet for like 3 days now and couldn't find any example on how to use Browserify in combination with AngularJS and Gulp.. So I have no clue.

I am developing an app, and I followed this guide. I like to require('fs') inside my mainCtrl.js, and use the function fs.readdirSync(); but gives me a typeError and returns fs.readdirSync is not a function, why isn't it working?

TypeError: fs.readdirSync is not a function
    at new module.exports (app.js:49)
    at Object.invoke (app.js:9502)
    at extend.instance (app.js:14347)
    at nodeLinkFn (app.js:13464)
    at compositeLinkFn (app.js:12896)
    at compositeLinkFn (app.js:12899)
    at compositeLinkFn (app.js:12899)
    at compositeLinkFn (app.js:12899)
    at publicLinkFn (app.js:12776)
    at app.js:6649

My code here:

app.js

'use strict';

require('angular');
require('angular-route');
require('angular-animate');

var mainCtrl = require('./controllers/mainCtrl');
var app = angular.module('myApp', ['ngRoute', 'ngAnimate'])

app.controller('mainCtrl', ['$scope', '$http', mainCtrl]);

mainCtrl.js

'use strict';
module.exports = function($scope, $http) {
    var fs = require('fs');

    console.log("fs in mainCtrl: ", fs); // this console logs Object {}
    var files = fs.readdirSync('data/');
    console.log("files in mainCtrl: ", files);
};  

Gulpfile.js

'use strict'; 

var gulp = require('gulp');
var browserify = require('browserify')

gulp.task('browserify', function() {
return browserify('./js/app.js')
    .bundle()
    .pipe(source('app.js'))
    .pipe(gulp.dest('./build'));

Solution

  • Wait, are you trying to use file-system functions in the browser?

    No, you cannot do that. Period. If you think about the security implications, you will see why.