Search code examples
javascriptnode.jsjsonnode-mysql

multiple string replace function not working in nodejs


Here I need to replace #tenant_id# in multiple files the input is coming from an json object as 1.

This is the first file to replace #tenant_id#:

INSERT INTO mst_designation (designation_name,tenant_id)
SELECT designation_name,#tenant_id# tenant_id FROM mst_designation  mdes
WHERE tenant_id = -1 
AND NOT EXISTS (SELECT 1 FROM mst_designation 
WHERE designation_name = mdes.designation_name AND tenant_id = #tenant_id#);

Here first #tenant_id# is replaced into 1 and second one is not replacing

The code for replacing string :

  const dirPath = path.join(__dirname + '/script/')

  filenames = fs.readdirSync(dirPath)

  filenames.forEach(files => {
            file = fs.readFileSync(dirPath + files, { encoding: 'utf8', flag: 'r' })

            fileReplace = file.replace("#tenant_id#", new_tenant_id)
            logger.log('silly', 'tenantOnBoard : tenant_id replace : Start ' + fileReplace);

             const queryCreateTenant = conPool.query(fileReplace)
             console.log(queryCreateTenant);
}

This is the code for replacing the string and here op is coming as

INSERT INTO mst_designation (designation_nametenant_id)
SELECT designation_name,#tenant_id# tenant_idFROM mst_designation  mdes
WHERE tenant_id = -1 
AND NOT EXISTS (SELECT 1 FROM mst_designation 
WHERE designation_name = mdes.designation_name AND tenant_id = #tenant_id#);

the #tenant_id# is not replacing on 2nd place How to resolve this issue


Solution

  • This is expected behavior in javascript. To replace a string multiple times you may use RegExp with g flag:

    fileReplace = file.replace(/#tenant_id#/g, new_tenant_id)