Collectives™ on Stack Overflow
Find centralized, trusted content and collaborate around the technologies you use most.
Learn more about Collectives
Teams
Q&A for work
Connect and share knowledge within a single location that is structured and easy to search.
Learn more about Teams
Sorry for so dumb question,
How i can in NodeJS read from file string by string some value, for example - url, and do operation with each string eventually?
var contents = fs.readFileSync('test.txt', 'utf8');
and what then?
It's need for browserstack+selenium testing.
I want run some links one-by-one, from file and do something with them.
Changed code below:
console.log(lines[i++])
line = (lines[i++])
driver.get(line);
driver.getCurrentUrl()
.then(function(currentUrl) {
console.log(currentUrl);
But it works once.
var str=fs.readFileSync('test.txt');
str.split(/\n/).forEach(function(line){})
C:\nodejstest>node test1.js
C:\nodejstest\test1.js:57
str.split(/\n/).forEach(function(line){
TypeError: str.split is not a function
at Object.<anonymous> (C:\nodejstest\test1.js:57:5)
at Module._compile (module.js:413:34)
at Object.Module._extensions..js (module.js:422:10)
at Module.load (module.js:357:32)
at Function.Module._load (module.js:314:12)
at Function.Module.runMain (module.js:447:10)
at startup (node.js:142:18)
at node.js:939:3
Works!
Much thanx!
Another (simpler) method would be to read the entire file into a buffer, convert it to a string, split the string on your line-terminator to produce an array of lines, and then iterate over the array, as in:
var buf=fs.readFileSync(filepath);
buf.toString().split(/\n/).forEach(function(line){
// do something here with each line
read file with readable stream and do your operation when you find '\n'
.
var fs=require('fs');
var readable = fs.createReadStream("data.txt", {
encoding: 'utf8',
fd: null
var lines=[];//this is array not a string!!!
readable.on('readable', function() {
var chunk,tmp='';
while (null !== (chunk = readable.read(1))) {
if(chunk==='\n'){
lines.push(tmp);
tmp='';
// this is how i store each line in lines array
}else
tmp+=chunk;
// readable.on('end',function(){
// console.log(lines);
// });
readable.on('end',function(){
var i=0,len=lines.length;
//lines is #array not string
while(i<len)
console.log(lines[i++]);
See if it works for you.
–
Thanks for contributing an answer to Stack Overflow!
- Please be sure to answer the question. Provide details and share your research!
But avoid …
- Asking for help, clarification, or responding to other answers.
- Making statements based on opinion; back them up with references or personal experience.
To learn more, see our tips on writing great answers.