我真的不明白为什么在将“fizbuzz”写入文件 test.txt 时当前会输出两行 - 我知道它正在执行查找和替换,但是有没有办法让查找和替换完成这样的操作它不会被 watch 功能捕获?
const watch = require('node-watch');
const replacer = require('replace-in-file');
const files_to_watch = [
'/users/gigatexal/code/nodejs/test.txt',
'/users/gigatexal/code/nodejs/test2.txt',
'/users/gigatexal/code/nodejs/test3.txt'
]
设置完成,解决问题
files_to_watch.forEach(f =>
{
watch(f,
{resursive: false},
function(evt, name){
replacer(
{
files: f,
from: 'fizbuzz',
to: 'foobar'
})
.then(change=>{console.log('the file ',f,' was fixed.')})
.catch(error=>(console.log('oops caught an error', error)));
}
)
}
);
运行上面的代码:
echo "fizbuzz" >> /users/gigatexal/code/nodejs/test2.txt
输出:
the file /users/gigatexal/code/nodejs/test.txt was fixed.
the file /users/gigatexal/code/nodejs/test.txt was fixed.
免责声明:我充其量只是一个中级/初学者 python DEV,所以这还不是惯用的 NodeJS 代码。我想了解如何到达那里。
最佳答案
由于您没有提供有关您的操作系统和程序中软件包版本号的太多信息,而且我没有足够的声誉来发表评论。我会尝试提供一些建议,但不太确定它们是否有帮助。
请务必使用最新版本的
node-watch
,v0.5.5。创建一个新函数(例如
handle_file
)来处理单个文件,以便于调试。function handle_file(f) { watch(f, function(evt, name) { replacer({ files: f, from: 'fizbuzz', to: 'foobar' }) .then(change => { console.log('the file %s was fixed.', f) }) .catch(error => { console.log('oops caught an error', error) }); }) } // now only need to do this files_to_watch.forEach(handle_file)
用一些日志替换
replacer
函数,看看是否检测到更改以及是否存在双重更改:function handle_file(f) { watch(f, function(evt, name) { console.log('%s changes.', name); }) }
然后也许您可以知道问题出在哪里。
关于javascript - 如何监视文件并执行查找替换,但不将查找替换捕获为监视文件中的事件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48017590/