How do i write a way to "backspace" a line in a text document

427 views Asked by At

Im creating scripts in WinCC unified where javascript is used, i have some code which finds specific 3 lines in a text file and deletes the values there, it works but i wish to also basicaly delete the whole line, as if you were to press backspace when there's no text on a text line.

The code

HMIRuntime.FileSystem.ReadFile(path, "utf8").then(
function(text) {
const lines = text.split('\n');
delete lines[noteNumber];
delete lines[noteNumber+1];
delete lines[noteNumber+2];
//HMIRuntime.Trace("lines:" +lines.join('\n')); 
FileSystem.WriteFile(path, lines.join('\n'),"utf8" )
});  

Thank you for any nice sould to help out.

I have tried the splicing but now the part which reads the .txt file and writes its data into HMI arrays is not updating and the values are no longer being read. The code which reads the .txt file is here

HMIRuntime.FileSystem.ReadFile(path, "utf8").then(
function(text) {

 for (let i = 0; i < maxNoteNumber; i++) {
 HMIRuntime.Trace("Trace Message"+ text.split('\n',i));
 Tags('strDate[' + i + ']').Write(text.split('\n')[i*3]);
 Tags('strName[' + i + ']').Write(text.split('\n')[i*3+1]);
 Tags('strNote[' + i + ']').Write(text.split('\n')[i*3+2]);
 }
 }).catch(function(errorCode) {
 HMIRuntime.Trace("read error:" + errorCode)
 for (let i = 0; i <= maxNoteNumber; i++) {
 Tags('strNote[' + i + ']').Write('\n')//emty overwrite
  }
  //create a emtpy file 
  HMIRuntime.FileSystem.WriteFile(path," ", 'utf8').then(
  function() {
    HMIRuntime.Trace('Write file finished sucessfully');
    }).catch(function(errorCode) {
     HMIRuntime.Trace('Write failed errorcode=' + errorCode);
});
});
1

There are 1 answers

11
CertainPerformance On

deleteing a property from an array will not stop that line from being used when .joining:

console.log(
  [1, , 3].join('\n')
);

const arr = [1, 2, 3];
delete arr[1];
console.log(
  arr.join('\n')
);

Splice the lines you want to remove out instead:

lines.splice(noteNumber, 3);

and then lines.join('\n') will give you what you want.