假设我们有一个文本文件,随机播放.txt包含以下内容
john
doe
user1
some keyword
last word
现在我们读到随机播放.txt文件,然后搜索 'user1' 关键字。如果任何行包含 'user1',然后我们将删除该行。
var fs = require('fs')
fs.readFile('shuffle.txt', {encoding: 'utf-8'}, function(err, data) {
if (err) throw error;
let dataArray = data.split('\n'); // convert file data in an array
const searchKeyword = 'user1'; // we are looking for a line, contains, key word 'user1' in the file
let lastIndex = -1; // let say, we have not found the keyword
for (let index=0; index<dataArray.length; index++) {
if (dataArray[index].includes(searchKeyword)) { // check if a line contains the 'user1' keyword
lastIndex = index; // found a line includes a 'user1' keyword
break;
}
}
dataArray.splice(lastIndex, 1); // remove the keyword 'user1' from the data Array
// UPDATE FILE WITH NEW DATA
// IN CASE YOU WANT TO UPDATE THE CONTENT IN YOUR FILE
// THIS WILL REMOVE THE LINE CONTAINS 'user1' IN YOUR shuffle.txt FILE
const updatedData = dataArray.join('\n');
fs.writeFile('shuffle.txt', updatedData, (err) => {
if (err) throw err;
console.log ('Successfully updated the file data');
});
});
在这里,如果一行包含 'user1' 关键字,我们将删除整行。新的随机播放.txt文件将不再包含带有“user1”关键字的行。更新后的随机播放.txt文件看起来像
john
doe
some keyword
last word
欲了解更多信息,请查看doc https://nodejs.org/dist/latest-v6.x/docs/api/fs.html.