wyc
wyc

Reputation: 55283

Why isn't this function modifying the final output?

I'm doing something simple: read a file, replace a character, and output the modified content:

#!/usr/bin/env node

var fs = require('fs')
  , filename = process.argv[2]

if (process.argv.length < 3) {
  console.log('Usage: node ' + process.argv[1] + ' FILENAME')
  process.exit(1)
}

function replaceCharacters(data) {
  data = data
    .replace(/"(?=\b|\*|')/g, '“')

  console.log(data)
}

function saveHtml(data) {
  fs.writeFile("untitled.html", data, function(err) {
    if (err)
      console.log(err)
    else
      console.log(data)
  })
}

fs.readFile(filename, 'utf8', function(err, data) {
  if (err) throw err

  replaceCharacters(data)

  saveHtml(data)
})

The problem is, replaceCharacters is not affecting the final output. Instead of curly opening quotes, I'm still getting the straight ones.

What am I doing wrong?

(The quotes do replace if a move the content from replaceCharacters into fs.readFile).

EDIT:

The value does change inside the function console.log(data) outputs the data with curly quotes.

Upvotes: 0

Views: 35

Answers (1)

T.J. Crowder
T.J. Crowder

Reputation: 1074949

It's replacing them, but never returning what it replaces:

function replaceCharacters(data) {
  data = data
    .replace(/"(?=\b|\*|')/g, '“')

  console.log(data)

  return data; // <====
}

Then when you use it:

    data = replaceCharacters(data)
//  ^^^^^^^

As you seem to know, replace creates a new string with the replacement, it doesn't update the string in place. (It can't, strings in JavaScript are immutable.) In your replaceCharacters function, you're updating the data argument with the result, but that doesn't change the variable that replaceCharacters was called with, just the argument within the function call. So just as you have to write data = data.replace(...) within your replaceCharacters function, you have to return the result from your replaceCharacters function and use that return value.

Upvotes: 5

Related Questions