如何使用nodejs的fs将文件写入父文件夹?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/20964372/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
how to write file to parent folder with fs of nodejs?
提问by AGamePlayer
I want to write a file to the current script folder's parent folder (and sometimes subdirectories to that parent folder)?
我想将文件写入当前脚本文件夹的父文件夹(有时是该父文件夹的子目录)?
How should I write the path?
路径应该怎么写?
Can this work?
这能行吗?
fs.writeFile(__dirname + '../sibling_dir/file.txt', 'test');
回答by loganfsmyth
Yes, that should work fine. The main issue I see is that you have no /between the dirname and the path.
是的,这应该可以正常工作。我看到的主要问题是/目录名和路径之间没有。
So what you have now is more like:
所以你现在拥有的更像是:
fs.writeFile('/tmp/module../sibling_dir/file.txt', 'test');
try this:
尝试这个:
fs.writeFile(__dirname + '/../sibling_dir/file.txt', 'test');
回答by jingyinggong
I tried this;
我试过这个;
fs.writeFile('../test.txt', 'test');
that works!
那个有效!
http://nodejs.org/api/fs.html#fs_fs_write_fd_buffer_offset_length_position_callback
http://nodejs.org/api/fs.html#fs_fs_write_fd_buffer_offset_length_position_callback
fs.write(fd, buffer, offset, length, position, callback)# Write buffer to the file specified by fd.
fs.write(fd, buffer, offset, length, position, callback)#将buffer写入fd指定的文件。
offset and length determine the part of the buffer to be written.
偏移量和长度确定要写入的缓冲区部分。
position refers to the offset from the beginning of the file where this data should be written. If position is null, the data will be written at the current position. See pwrite(2).
位置是指从文件开头的偏移量,该数据应写入该位置。如果 position 为 null,则数据将写入当前位置。请参阅 pwrite(2)。
The callback will be given three arguments (err, written, buffer) where written specifies how many bytes were written from buffer.
回调将提供三个参数(err、write、buffer),其中 write 指定从缓冲区写入的字节数。
Note that it is unsafe to use fs.write multiple times on the same file without waiting for the callback. For this scenario, fs.createWriteStream is strongly recommended.
请注意,在不等待回调的情况下对同一文件多次使用 fs.write 是不安全的。对于这种情况,强烈建议使用 fs.createWriteStream。
On Linux, positional writes don't work when the file is opened in append mode. The kernel ignores the position argument and always appends the data to the end of the file.
在 Linux 上,以追加模式打开文件时,位置写入不起作用。内核忽略位置参数并始终将数据附加到文件末尾。

