21

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');
1
  • 3
    Also look at path (path.resolve would help you here.) Commented Jan 7, 2014 at 12:55

3 Answers 3

31

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');
Sign up to request clarification or add additional context in comments.

Comments

9

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

fs.write(fd, buffer, offset, length, position, callback)# Write buffer to the file specified by 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).

The callback will be given three arguments (err, written, buffer) where written specifies how many bytes were written from buffer.

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.

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.

1 Comment

Taking out the __dirname will write the file relative to the current working directory rather than relative to the script file.
0

Another way of approaching it if you know the paths. You would execute the code in current/index.js and you want to create a file as new/sibling_dir/file.txt:

.
├── current
│   └── index.js
└── new
    └── sibling_dir
        └── file.txt

So in my case what I did was:

// in index.js
const fs = require('fs');

fs.writeFile(__dirname.replace('current', 'new/sibling_dir/') + 'file.txt', 'test');

Basically replacing in the path the current directory by the new one. This executed from index.js in the other directory will be writing test in the new/sibling_dir/file.txt.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.