How to Set or Change Line Endings in a Text File using Node.js
Controlling the line endings of our text files makes it easy to transfer properly formatted plain text content across Mac, Windows & Unix operating systems.
Using the below ready-to-run Node.js code examples, we can take advantage of a free API that allows us to quickly set the line ending type for our text files. In the lineEndingType parameter, we can specify ‘Windows’ for carriage return & line feed, ‘Unix’ for newline, and ‘Mac’ for carriage return.
To authorize our API requests, we just need a free-tier API key, which will allow up to 800 API calls per month and no additional commitment.
We can start structuring our API call by installing the SDK. Let’s go ahead and either run the following command:
npm install cloudmersive-convert-api-client --save
Or, alternatively, add the following snippet to our package.json:
"dependencies": {
"cloudmersive-convert-api-client": "^2.6.3"
}
And then we include the below code in our file to make our request:
var CloudmersiveConvertApiClient = require('cloudmersive-convert-api-client');
var defaultClient = CloudmersiveConvertApiClient.ApiClient.instance;
// Configure API key authorization: Apikey
var Apikey = defaultClient.authentications['Apikey'];
Apikey.apiKey = 'YOUR API KEY';
var apiInstance = new CloudmersiveConvertApiClient.EditTextApi();
var lineEndingType = "lineEndingType_example"; // String | Required; 'Windows' will use carriage return and line feed, 'Unix' will use newline, and 'Mac' will use carriage return
var inputFile = Buffer.from(fs.readFileSync("C:\\temp\\inputfile").buffer); // File | Input file to perform the operation on.
var callback = function(error, data, response) {
if (error) {
console.error(error);
} else {
console.log('API called successfully. Returned data: ' + data);
}
};
apiInstance.editTextChangeLineEndings(lineEndingType, inputFile, callback);
Now we can have better control over the interoperability of our text files.