preserveFormatting is true by default. The following examples show how
separatorParts and separatorHostname work while preserving formatting.
Given an empty hosts file
await assignHostnames('1.2.3.4', ['hostname1'])
// updates it to
// 1.2.3.4{tab}hostname1to insert a space instead of a tab for new host entries:
await assignHostnames('5.6.7.8', ['hostname2'], { separatorParts: ' ' })
// adds the line
// 5.6.7.8{space}hostname2Given a hosts file
1.2.3.4 hostname1{tab}hostname2await assignHostnames('1.2.3.4', ['hostname3'])
// updates /etc/hosts to
// 1.2.3.4 hostname1{tab}hostname2{space}hostname3to insert a tab instead of a space for new hostnames:
await assignHostnames('1.2.3.4', ['hostname4'], { separatorHostname: '\t' })
// updates /etc/hosts to
// 1.2.3.4 hostname1{tab}hostname2{space}hostname3{tab}hostname4The following examples show how separatorParts and separatorHostname work when preserveFormatting is false.
Given a hosts file
1.2.3.4{space}hostname1{space}#some comment
5.6.7.8{space}hostname2Assigning any hostname will normalize all whitespace
await assignHostnames('5.6.7.8', ['hostname3'], { preserveFormatting: false })
// updates it to
// 1.2.3.4{tab}hostname1{tab}#some comment
// 5.6.7.8{tab}hostname2{space}hostname3If we assign an existing hostname then the file isn't touched regardless of whitespace.
Let's reset the host file to show what I mean:
1.2.3.4{space}hostname1{space}#some comment
5.6.7.8{space}hostname2and assign an existing hostname
await assignHostnames('5.6.7.8', ['hostname2'], { preserveFormatting: false })
// doesn't modify the hosts fileLet's separate the parts via two spaces instead of a tab.
Given a hosts file
1.2.3.4{tab}hostname1{tab}#some comment
5.6.7.8{tab}hostname2{tab}hostname3await assignHostnames('5.6.7.8', ['hostname4'], {
preserveFormatting: false,
separatorParts: spaces[2],
})
// updates it to: (hyphen represents a space)
// 1.2.3.4--hostname1--#some comment
// 5.6.7.8--hostname2-hostname3-hostname4Let's separate the hostnames by two spaces instead of one
Given a hosts file
1.2.3.4{space}hostname1{tab}hostname2await assignHostnames('1.2.3.4', ['hostname3'], { separateHostname: spaces[2] })
// updates it to: (hyphen represents a space)
// 1.2.3.4{tab}hostname1--hostname2--hostname3