Search code examples
javascriptnode.jsgulp

How can I find text in a file and replace it?


I need to write a function for the gulp.
The function should:
1. Open file (style.min.css)
2. Find all lines with the given text (img/sprite.png)
3. Replace all found lines with (../img/sprite.png)

To simplify the task, I include a plugin (replace-in-file)
I am not good at Node.js but I tried...
Please help me make it right.
If you want you can show how to do this without using a plugin (replace-in-file).
But you can also use the plugin...

const build = ('build/')
const replace = require('replace-in-file')
const config = {
    build: {
        style: build + 'css'
    }
}

function fixSprites() {
    const results = replace.sync({
        files: config.build.style + '/style.min.css',
        from: 'img/sprite.png',
        to: '../img/sprite.png',
        countMatches: true,
    })
    return src(config.build.style + '/style.min.css')
        .pipe(replace(results))
}

exports.fixSprites = fixSprites()

Solution

  • I used a plugin 'replace-in-file'!
    This is the out of the box gulp solution
    Replace all lines of a similar type with others.
    Example: replace img/sprite.png with ../img/sprite.png

    enter image description here

    const { series } = require('gulp')
    const replace = require('replace-in-file')
    
    function updateRedirects(done) {
        replace({
            files: 'build/css/style.min.css',
            from: /img\/sprite.png/g, // img/sprite.png – Replace this.
            to: '../img/sprite.png', // ../img/sprite.png – Replace with this.
            countMatches: true,
        }, done)
    }
    
    exports.build = series(updateRedirects) // Start