我有一个脚本读取文件并按模式比较字符串,如果返回false,它将删除.txt文件上的行。
这是我的代码
const readline = require('readline');
const lineReplace = require('line-replace')
const fs = require('fs');
const inputFileName = './outputfinal.txt';
const readInterface = readline.createInterface({
input: fs.createReadStream(inputFileName),
});
let testResults = [];
readInterface.on('line', line => {
testResult = test(line);
console.log(`Test result (line #${testResults.length+1}): `, testResult);
testResults.push({ input: line, testResult } );
if (testResult == false){
console.log(`Line #${testResults.length} will get deleted from this list`);
lineReplace({
file: './outputfinal.txt',
line: testResults.length,
text: '',
addNewLine: false,
callback: onReplace
});
function onReplace({file, line, text, replacedText}) {
};
};
});
// You can do whatever with the test results here.
//readInterface.on('close', () => {
// console.log("Test results:", testResults);
//});
function test(str){
let regex = /^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,3})+$/; // email regex
str = str.split(",");
// string should be of length 3 with str[1] number of length 7
if(str && str.length === 3 && Number(str[1]) && str[1] ) {
let temp = str[0].split("-");
// check for 85aecb80-ac00-40e3-813c-5ad62ee93f42 separately.
if(temp && temp.length === 5 && /[a-zA-Z\d]{8}/.test(temp[0]) && /[a-zA-Z\d]{4}/.test(temp[1]) && /[a-zA-Z\d]{4}/.test(temp[2]) && /[a-zA-Z\d]{4}/.test(temp[3]) && /[a-zA-Z\d]{12}/.test(temp[4])){
// email regex
if(regex.test(str[2])) {
return true;
} else {
return false;
}
} else {
return false
}
} else {
return false;
}
}
但是不起作用,没有这样的文件或目录返回错误,我不认为这是执行换行脚本的正确方法
首先,如果错误是“没有这样的文件或目录”,是因为该文件不存在。请首先检查文件在项目的同一根目录中是否存在。
[第二,不要使用“ line-replace”库,如果您检查代码,则将创建一个tmp文件,并用替换内容重写tmp中的所有文件。完成此过程后,tmp文件将重命名为原始文件。
第三,如果您分析代码,则“ lineReplace”是异步的。因此,有时会尝试同时打开多次文件,然后再次将其写入。这将产生意想不到的结果。
最佳建议是您必须了解nodejs中文件的工作方式和承诺(异步):
如果看到下一个代码,将看到以下步骤:
readline
接口const fs = require('fs');
const readline = require('readline');
async function replaceLineWithConditional(pathFile, conditional) {
// tmpFile name
const tmpFilePath = `${pathFile}.tmp`;
// Create write stream
const tmpStream = fs.createWriteStream(tmpFilePath);
// Process it
const processFile = new Promise((resolve, reject) => {
const rl = readline.createInterface({
input: fs.createReadStream(pathFile),
});
// Process line
rl.on("line", (input) => {
try {
if (conditional(input)) {
tmpStream.write(input); // input
tmpStream.write("\n"); // linejump
}
} catch (err) {
// Reject error
reject(err);
}
});
// Finish
rl.on("close", () => {
try {
// Move the tmpFile
tmpStream.close();
fs.renameSync(tmpFilePath, pathFile);
// Resolve it
resolve(true);
} catch (err) {
// Reject error
reject(err);
}
});
});
try {
// Await the promise
return await processFile;
} catch (err) {
// Delete the tmp file and throw the error
tmpStream.close();
fs.unlinkSync(tmpFilePath);
throw err;
}
}
因此您可以将条件函数过程作为回调来调用该函数。例如,我要保留长度大于3且不以“ a”开头的所有行:
// async/await:
await replaceLineWithConditional("./test.txt", (line) => {
return line.length > 3 && /^[^a]/.test(line);
});
// then/catch:
replaceLineWithConditional("./test.txt", (line) => {
return line.length > 3 && /^[^a]/.test(line);
}).then(...).catch(...);
input:
Hi
Hello
abcdef
a
lalalal
输出:
Hello
lalalal
如果您不希望文件以结尾行结尾。 (请注意:Why should text files end with a newline?)这可能是测验fs
库中知识的测验问题:)