Node.jsrecursion地创build和删除一个文件

我认为这将是一个很酷的实验,有一个for循环,并创build一个文件hello.txt,然后删除与解除链接。 我想如果fs.unlink是Node中的删除文件过程,则fs.link必须是创build文件。 但是,我的代码只会删除,而不会创build,甚至不会创build一次。 即使我将fs.link代码分离成单独的文件,它仍然不会创build我的文件hello.txt。

以下是我的代码:

var fs = require('fs'), for(var i=1;i<=10;i++){ fs.unlink('./hello.txt', function (err) { if (err){ throw err; } else { console.log('successfully deleted file'); } fs.link('./hello.txt', function (err) { if (err){ throw err; } else { console.log('successfully created file'); } }); }); } 

http://nodejs.org/api/fs.html#fs_fs_link_srcpath_dstpath_callback

谢谢!

使用'w'参数的fs.open()将会创build一个文件。 随着您的继续,您可能会遇到与代码有关的第二个问题,如下所示:

 /srv/node/test $ node makekill.js successfully created file successfully created file successfully created file successfully created file successfully created file successfully created file successfully created file successfully created file successfully created file successfully created file successfully closed file /srv/node/test/makekill.js:13 throw err; ^ Error: ENOENT, No such file or directory './hello11.txt' 

通过一些额外的日志logging,您将看到您使用的代码实际上并没有通过“hello10.txt”触发“hello1.txt”的创build操作,然后是相同的删除操作。 (或者在你的示例中,删除,然后是创build,尽pipe在debugging的时候我改变了这个,因为创build/删除对我更有意义。)

更重要的是,asynchronouscallback似乎都使用最终的“i”值,而不是相关循环中的“i”的值。

长话短说,我通过为一个给定的文件名执行所需的创build/删除的单独函数,然后从for循环中调用这个函数来使这个概念工作。 这似乎是一个更可靠的方法来确保在整个动作序列中使用“i”的预期值,而不是在初始步骤和callback步骤之间进行更改。

 var fs = require('fs'); function openUnlink(name) { console.log(name); fs.open(name, 'w', function (err) { console.log(' + ' + name); fs.unlink(name, function (err) { console.log(' - ' + name); }); }); } for (var i=1;i<=10;i++) { openUnlink('hello'+i+'.txt'); } 

fs.link创build一个符号链接(这是一个“链接文件”,指向另一个文件)

你想要fs.writeFile

答案是正确的,只是评论为什么。 在Unix中(这是在这里近似的Unix系统调用API),unlink用于删除到文件的链接。 当没有进一步的硬链接时,该文件被视为被删除。