C
C
Coder3212016-10-13 01:21:26
JavaScript
Coder321, 2016-10-13 01:21:26

How to insert text/code into a file using node?

I have a js file, and depending on the configuration, I need to generate code in certain places, how can I do this?

Answer the question

In order to leave comments, you need to log in

2 answer(s)
S
SergeyBugai, 2017-01-09
@Coder321

Everything is very simple:

const fs = require('fs');
const StringDecoder = require('string_decoder').StringDecoder;
const decoder = new StringDecoder('utf8');

// читаем файл
 fs.readFile(path, (e, file) => {
     if (e) throw new Error(e);
     file = decoder.write(file); // конвектируем в строку
     file = file.replace('строка которую меняем', 'строка на которую меняе');

     fs.writeFile(patch, file, callback); // записываем обратно
})

A
Alexander Taratin, 2016-10-13
@Taraflex

Take a simple templating engine whose syntax won't break js. For example twitter.github.io/hogan.js
Rewrite the modified js code into the template engine language.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question