Node: Fix line endings by platform

By Eric Downing. Filed in Linux, Node, Windows  |  
TOP del.icio.us digg

Using a Node script to query a database to do corrections was working fine on my local Windows based system until we tried to automate the process. We moved it to a Jenkins server which happened to be on a Linux system and the script stopped working. After some debugging it turned out that the way we were attempting to differentiate data returns from the queries depended on the line ending.

On a Windows system, the line endings are ‘\r\n’ or carriage return, new line. This had worked well while we were running the script locally, but once it went to the Linux system the line endings were just a ‘\n’ or new line. The line ending was not being matched so this led us to figure out how to tell what platform was being used. The process.platform variable contains the platform name.

The process.platform returns ‘win32’ for Windows, ‘darwin’ for MacOS and ‘linux’ for linux systems. There are other platforms supported but these are all that mattered to us. Using this variable we were able to replace the line endings and the data started working as expected on all our platforms.

The following code snippet sets the lineendings for our sql code:

let platform = process.platform;
let lineendings = '\n';
if (platform == 'win32') {
    lineendings = '\r\n';
}

Tags: ,

Leave a Reply