0

I've spent the past hours trying to figure out what the issue with the code below is. What I am trying to do is write the content of a request body to a file, and then remove the \ns from there with enter (I am saving markdown and I need the double enter to keep the markdown valid).

When running the following in my router:

// working code
... 
if (shell.exec(`echo "${blog.content}" > ${blogTitleWithDash}.md`).code !==0) {
    logger.error('Error! writing to file failed!');
    return res.status(500).json('Error! Something went wrong');
}
// replace \n
if (shell.exec(`awk '{gsub(/\\\\n/,\"\\n\\n\")}1' ${blogTitleWithDash}.md > ${blogTitleWithDash}2.md`).code !== 0) {
    logger.error('Error! Awk failed!');
    return res.status(500).json('Error! Something went wrong');
}

it seems like nothing is being changed in the file. I've tried replacing other characters, but that didn't work. However, taking the string which is passed to shell.exec() and running it from the command line works perfectly: awk '{gsub(/\\n/,"\n\n")}1' This-is-a-test-blog.md > This-is-a-test-blog2.md

Am I misusing shelljs or did I mess up the awk command?

oguz ismail
  • 1
  • 16
  • 47
  • 69
David Buzatu
  • 624
  • 8
  • 18
  • Just a tip. Replaced old and deprecated backtics with parentheses if you code accept it. Ex `$(awk '{gsub(/\\\\n/,\"\\n\\n\")}1' ${blogTitleWithDash}.md > ${blogTitleWithDash}2.md)` – Jotne Aug 13 '21 at 20:09
  • Thank you for your suggestion Jotne, but that didn't work with `shelljs`. However, your suggestion got me thinking about `sed` and I fixed my issue using: ```shell.sed('-i', /\\n/g, '\n\n', `${blogTitleWithDash}.md`)``` – David Buzatu Aug 13 '21 at 21:21

0 Answers0