How to Split Text Files into Lines using Node.js
Each line of a text file can be separated and stored independently with minimal effort.
We can easily divide our text files into separate objects — with each object containing its original line number & line contents — using the below code. We’ll be calling a free API service to do so, and all we’ll need is a free-tier API key to authorize our requests (this will allow up to 800 API calls per month with no additional commitments).
Our first step is to install the SDK. We can do that in one of two ways — either by running the following command:
npm install cloudmersive-convert-api-client --save
Or by adding the below snippet to our package.json:
"dependencies": {
"cloudmersive-convert-api-client": "^2.6.3"
}
After that, we can include the below code examples in our file, and we’re all set:
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.SplitDocumentApi();
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.splitDocumentTxtByLine(inputFile, callback);