Read file with fs module and keep the original file

Viewed 60

I'm actually working on a NodeJS API that send mail.

index.handlebars is a template that I want to use everytime that I need to send an email

So I use Node File Systeme (fs) to readFileSync() and then replace() the data need before sending email to the user.

Here is an exemple :

const readMe = fs.readFileSync('./mails/index.handlebars', 'utf8', (error, data) => {
  if (error) {
    console.log(error);
  } else {
    data = data.toString('utf8').replace('{%CONFIRMATION%}', "SELLER AS VALIDATE YOUR ORDER")
    return data
  }
})
console.log(readMe);

First sometimes, replace() is not working for me and nothing happend. I don't know why.

But when it work, my goal is to not overwrite index.handlebars. What I mean by that is replace() all the stuff and then send it BUT keep index.handlebars as it was before replace(). Is it possible ?

Thanks a lot.

1 Answers

The fs module provides fs.readFile (read file asynchronously, takes a callback) and fs.readFileSync (read synchronous, does not require a callback).

You are currently mixing up the 2 signatures in trying to do a synchronous read with a callback.

To use readFileSync (synchronous), you should

// synchronous without callback
const data = fs.readFileSync('./mails/index.handlebars', { encoding: 'utf8', flag: 'r' })
const replaced = data.replace('{%CONFIRMATION%}', "SELLER AS VALIDATE YOUR ORDER")
console.log(replaced);

For readFile (asynchronous), you use the callback

// asynchronous with callback
fs.readFile('./mails/index.handlebars', 'utf8', (error, data) => {
    if (error) {
        console.log(error);
    } else {
        data = data.replace('{%CONFIRMATION%}', "SELLER AS VALIDATE YOUR ORDER")
        // perform necessary operations on data
        console.log(data);
    }
})
Related