2

I try using fs.open(). But when the file not exist, the data exist. Below is my code:

fs.open('person.json', 'w', function (err, data) {
  if (err) throw err;
  console.log(data)
});

console.log(data) result is

3

Why is that? Where the 3 come from?

My purpose is to read the file if exist and create new file if doesn't exist. How to do it in node.js?

4 Answers 4

2

'3' - is a file descriptor. https://nodejs.org/api/fs.html#fs_file_descriptors

'w' - Open file for writing. The file is created (if it does not exist) or truncated (if it exists).

Use 'r+' - Open file for reading and writing. An exception occurs if the file does not exist.

https://nodejs.org/api/fs.html#fs_file_system_flags

Sign up to request clarification or add additional context in comments.

Comments

2
  1. It sounds like the FIRST thing you want to do is call fs.statSync(), to check if the file exists.

  2. If it exists, then call fs.open("r"), to read it.

  3. Otherwise, it sounds like you want to create it. fs.open("w"), as you've done above, should work fine.

  4. fs.open returns a file descriptor. I suspect that's probably the "3" you're asking about.


Addendum 4/24/19

Historically speaking (other languages, other times), the idea of using "exceptions" to handle "control flow" is frankly HORRIFYING.

But repeatdomiau makes a valid point. The documentation does seem to suggest simply opening the file, and handling any exception that might arise:

https://nodejs.org/api/fs.html

// Check if the file exists in the current directory, and if it is writable.
fs.access(file, fs.constants.F_OK | fs.constants.W_OK, (err) => {
  if (err) {
    console.error(
      `${file} ${err.code === 'ENOENT' ? 'does not exist' : 'is read-only'}`);
  } else {
    console.log(`${file} exists, and it is writable`);
  }
});

Using fs.access() to check for the accessibility of a file before calling fs.open(), fs.readFile() or fs.writeFile() is not recommended. Doing so introduces a race condition, since other processes may change the file's state between the two calls. Instead, user code should open/read/write the file directly and handle the error raised if the file is not accessible.

3 Comments

I use fs.existsSync() instead of statSync(), there are more example in the web for existsSync(). Then when I use fs.open (file exist), I still get the same result, which is "3". So I choose to use readFile(). Thank you.
It doesn't matter if "there are more examples". Look at the documentation I cited above. "fs.exists()" is DEPRECATED. You should NOT use it in any new code. Use fs.stat()" instead.
From node documentation: Using fs.stat() to check for the existence of a file before calling fs.open(), fs.readFile() or fs.writeFile() is not recommended. Instead, user code should open/read/write the file directly and handle the error raised if the file is not available.
0

you can use "ax" mode means Open for appending. If the file does not exist, it is created but the file is opened in exclusive mode. or can use "a+" mode means Open for reading and appending. If the file does not exist, it is created and '3' you are getting is a file descriptor ("On POSIX systems, for every process, the kernel maintains a table of currently open files and resources. Each open file is assigned a simple numeric identifier called a file descriptor." At the system-level, all file system operations use these file descriptors to identify and track each specific file. Windows systems use a different but conceptually similar mechanism for tracking resources. To simplify things for users, Node.js abstracts away the specific differences between operating systems and assigns all open files a numeric file descriptor. The fs.open() method is used to allocate a new file descriptor. Once allocated, the file descriptor may be used to read data from, write data to, or request information about the file.)

Comments

0

Try to check this code, It might work for you

const fs = require('fs');
const readline = require('readline-sync'); 

     // Check if the file exists in the current directory, and if it is writable.

            var path = ("file.txt"); // Path to your file
            var data = output; // this variable contains some data to insert

            fs.access(path, fs.constants.F_OK | fs.constants.W_OK, (err) => {
              if (err) {
                  fs.writeFileSync('file.txt', output, 'utf-8'); //create a new file
              } else {
                    try {
                    fs.writeFileSync(path, data, {flag:'a+'}); //append mode: adds text to actually existing file 
                  } catch(err) {
                    console.error(err); //shows error if script can't add data 
                 }                    
                 }
             });

Also you must install readline-sync module from npm, also change 'path' and 'output' variables to make this work. After this if you will don't have file, script make a new one, if will exist, will insert actual data to your file without reseting it.

P.S: Sorry for my English language.

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.