Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do you split a text file using the split method in NodeJS?

Tags:

node.js

fs

I want to split a text file that I used NodeJS FS to read. When I try, it returns an array that includes encoded information.

I already tried decoding the array, but it didn't return anything.

Code:

const fs = require("fs"); 
var data = fs.readFileSync("data.txt", 'utf-8'); 
var dataArr = data.split('s');  
console.log(dataArr); 

Output:

[ '��t\u0000e\u0000', '\u0000t\u0000' ]
[ '��t\u0000e\u0000', '\u0000t\u0000' ]

Text File:

test

I want it to return:

["te", "t"]
like image 644
Jason Yang Avatar asked Sep 05 '25 02:09

Jason Yang


1 Answers

According to the nodejs website fs.readFileSync return either Buffer or a String. The best way to do this would be to use fs.readFileSync without the uft-8 option then change the buffer to uft-8 using toString('utf8')

Example from your code

const fs = require("fs"); 
var data = fs.readFileSync("data.txt"); 
var dataArr = data.toString('utf8').split('s');  
console.log(dataArr); 
like image 181
sassy_rog Avatar answered Sep 07 '25 23:09

sassy_rog