mtpultz
mtpultz

Reputation: 18268

Using Grunt to Replace Text in a File

I'm trying to get Grunt to replace a path reference and I'm not sure what I'm doing wrong. This looks like it should work. Essentially, I'm copying a Bootstrap file up a directory and changing the @import paths, so I'm just trying to replace 'bootstrap/' with the new destination path 'MY/NEW/DEST/PATH/bootstrap'. I don't want to use a module for something as straight forward as this, seems needless. Everything works but the replace.

var destFilePath = path.join(basePath, file);

// Does the file already exist?
if (!grunt.file.exists(destFilePath)) {

    // Copy Bootstrap source @import file to destination
    grunt.file.copy(

        // Node API join to keep this cross-platform
        path.join(basePath, 'bootstrap/_bootstrap.scss'),
        destFilePath
    );

    // Require node filesystem module, since not a global
    var fs = require('fs');

    // Replace @import paths to be relative to new destination                                
    fs.readFile(destFilePath, 'utf8', function(err, data) {

        // Check for any errs during read
        if (err) {
            return grunt.log.write(err);
        }

        var result = data.replace('/bootstrap\//g', 'bootstrap/bootstrap/');

        fs.writeFile(destFilePath, result, 'utf8', function(err) {
            return grunt.log.write(err);
        });
    });
}

Upvotes: 1

Views: 1223

Answers (1)

Robert Levy
Robert Levy

Reputation: 29073

You wrapped your regex in quotes - don't do that and it should work fine:

var result = data.replace(/bootstrap\//g, 'bootstrap/bootstrap/');

Upvotes: 1

Related Questions