Node.js 在nodejs中如何获取fs.readfile回调中的路径

Node.js 在nodejs中如何获取fs.readfile回调中的路径,node.js,Node.js,我正在使用chokidar watcher监视目录。我想在fs.readFile的回调中输入路径名。如果我写代码如下: watcher.on('add', path => { var log = console.log.bind(console); log(`File ${path} has been added`); fs.readFile(path,'utf-8', function(err, data,path)

我正在使用chokidar watcher监视目录。我想在fs.readFile的回调中输入路径名。如果我写代码如下:

watcher.on('add', path => {
            var log = console.log.bind(console);
            log(`File ${path} has been added`);
            fs.readFile(path,'utf-8', function(err, data,path) {
log(`File ${path} has been read`);
......
......
以下是输出:

已添加文件test1.txt

未定义的文件已被读取

如何在fs.readfile回调中获取path的值(path,'utf-8',callback..,这里回调只包含两个参数,
1-error,2-data
。error和data的值被传递到各自的参数中。(请注意,第一个始终用于error,另一个用于data)

您正在将第三个参数添加到此回调中,该参数永远不会包含任何值,因此您会看到
未定义
,因为
fs
模块从未填充除
error
data
之外的任何其他参数。因此,首先从回调参数中删除该参数,您的回调应该如下所示

 fs.readFile(path,'utf-8', function(err, data) {..
现在您应该看到控制台中打印的文件名

此外,您可以始终使用
nodejs的
path
模块

path.basename('pathToFile')

将返回指定为参数的路径中的文件名

fs.readFile()
回调中删除
path
参数,您就可以了。