NodeJS,fs.readFileSync逐string读取和操作。 怎么样?

对不起,这么愚蠢的问题,

我怎么可以在NodeJS从文件string读取string的一些价值,例如 – url,并最终做每个string的操作?

var contents = fs.readFileSync('test.txt', 'utf8'); 

那么呢?

这是需要浏览器+seleniumtesting。 我想从文件中逐个运行一些链接,并对它们进行一些操作。

更改了下面的代码:from

 console.log(lines[i++]) 

 line = (lines[i++]) driver.get(line); driver.getCurrentUrl() .then(function(currentUrl) { console.log(currentUrl); 

但它有一次。

 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 

作品! 多好!

另一种(更简单的)方法是将整个文件读入缓冲区,将其转换为string,在行终止符上拆分string以产生行数组,然后遍历数组,如下所示:

 var buf=fs.readFileSync(filepath); buf.toString().split(/\n/).forEach(function(line){ // do something here with each line }); 

用可读的stream读取文件,并在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++]); }); 

看看它是否适合你。