Nodejs, who wants to realize fis’s inline function, wrote the following code. Is there a simpler way to write it? ?

  node.js, question

Code logic

  1. Create two files

  2. Read in final_file and put its contents into finaldata

  3. Finaldata is processed and the src_file file it introduces is extracted.

  4. Read src_file and assign its value to finaldata

  5. Then write finaldata to final_file.

var fs = require('fs');
 var finalData;
 var arrayFile =[];
 var arrayStr=[];
 fs.writeFile('src_file.js', 'fsdfsdfwsffffffffffffffffffffffffffffff', function(err, fd) {
 console.log('create newe new_file');
 });
 
 fs.writeFile('final_file.js', '__inline("src_file.js")', function(err, fd) {
 console.log('create newe new_file');
 });
 fs.readFile('final_file.js', 'utf8', function(err, data) {
 var finalData = data;
 arrayFile = findInlineArray(data);
 for(var i in arrayFile){
 fs.readFile(arrayFile[i],"utf8",function(err, fd) {
 finalData = fd;
 fs.writeFile('final_file.js', finalData, function(err, fd) {
 console.log('success');
 });
 });
 bracket
 
 function  findInlineArray(data) {
 var arrayFile = [];
 var patt = /(__inline\(['"]).*(?  =['"]\))/;
 //But this way of writing can only match the occurrence of an inline situation.
 //Need improvement
 var result = patt.exec(data)[0].replace(patt.exec(data)[1],'');
 var tempReadFile;
 arrayFile.push(result);
 return arrayFile;
 bracket
 });

If you don’t mind using synchronization, you can do this.

const fs = require('fs')
 
 fs.readFile('final_file.js',(err,content) => {
 content = content.toString()
 
 Content = content.replace (/inline \ (\ s * ["'] (["'] plus) ["] \ s * \)/g, (str, script) = > {.
 
 if (fs.existsSync(script)) {
 try {
 return fs.readFileSync(script,'utf8')
 } catch(err) {
 return str
 bracket
 bracket
 
 return str
 })
 
 fs.writeFile('final_file.js', content)
 })

If you don’t like synchronization, you can do it this way.

const fs = require('fs')
 
 var readFile = script => {
 return new Promise((resolve,reject) => {
 fs.readFile(script, (err,content) => {
 if (err) {
 return resolve(null)
 bracket
 
 resolve(content)
 })
 })
 bracket
 
 readFile('final_file.js')
 .then(content => {
 content = content.toString()
 
 var promises = []
 
 Constantine _ reg =/_ inline \ (\ s * ["'] (["]) plus) ["] \ s * \)/g
 
 content.replace(INLINE_REG , (str,script) => {
 promises.push(readFile(script))
 })
 
 return Promise.all(promises)
 .then(contents => {
 var i = 0
 content = content.replace(INLINE_REG , (str, script) => {
 Return (contents [igadd] || str).toString ()
 })
 
 return content
 })
 })
 .then(content => {
 fs.writeFile('final_file.dist.js', content)
 })