admin管理员组

文章数量:1430924

When I ran my mands in Node mand prompt, they worked fine.

fs= require('fs')
fs.readdir('.',function(e,files){console.log(files)})

However, when I inserted the lines above into my gruntfile.js, the callback function was not executed at all. Can you please tell me how I can get a list of files in a certain folder in Gruntfile.js?

Gruntfile.js:

'use strict';

var fs= require('fs');

module.exports= function(grunt){

    var configs = require('load-grunt-configs')(grunt);
    grunt.initConfig(configs);

    require('load-grunt-tasks')(grunt);

    fs.readdir('.', function(err,files){
        console.log(files);
    })


}

When I ran my mands in Node mand prompt, they worked fine.

fs= require('fs')
fs.readdir('.',function(e,files){console.log(files)})

However, when I inserted the lines above into my gruntfile.js, the callback function was not executed at all. Can you please tell me how I can get a list of files in a certain folder in Gruntfile.js?

Gruntfile.js:

'use strict';

var fs= require('fs');

module.exports= function(grunt){

    var configs = require('load-grunt-configs')(grunt);
    grunt.initConfig(configs);

    require('load-grunt-tasks')(grunt);

    fs.readdir('.', function(err,files){
        console.log(files);
    })


}
Share Improve this question edited Feb 20, 2015 at 3:26 TrongBang asked Feb 20, 2015 at 1:02 TrongBangTrongBang 9671 gold badge12 silver badges25 bronze badges 3
  • please provide the relevant Gruntfile code – Seth Commented Feb 20, 2015 at 1:26
  • I answered a similar question here: stackoverflow./questions/28597314/… – sctskw Commented Feb 20, 2015 at 1:34
  • @sctskw: It's actually not the answer. Sorry guy – TrongBang Commented Feb 20, 2015 at 3:27
Add a ment  | 

1 Answer 1

Reset to default 7

To get the node file system working inside grunt, the task needs to be asynchronous . Here is the code:

var fs = require('fs');

module.exports = function(grunt) {


  grunt.registerTask('showFiles', function() {
    var done = this.async(); // creating an async variable

    fs.readdir('.', function(err, files) {
      console.log(files);
      done(); // call when the task is done
    })
  })

  var files = fs.readdirSync('.');
  console.log('Showing Files Read Synchronously');
  console.log(files);
}

//output

▶ grunt showFiles
Showing Files Read Synchronously
[ 'Gruntfile.js', 'index.js', 'node_modules', 'test.js' ]
Running "showFiles" task
[ 'Gruntfile.js', 'index.js', 'node_modules', 'test.js' ]

本文标签: javascriptNode fsreaddir not working in Grunt fileStack Overflow