Node fs.readdir not working in Grunt file
gruntjs, javascript, node.js
Solution
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' ]
Problem
When I ran my commands in Node command 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); }) } ```