3

I am just trying some code on NodeJS, i am new to NodeJS. I have write following block of code.

 var fs = require('fs'),
    os = require('os');

var filename = 'Server.ini';
var serverData = os.hostname() + "\n" + os.platform() + "\n" + os.type() + "\n";

fs.existsSync(filename, function(exists) {
    if(exists) {
        console.log("1. " + filename + " file found. Server needs to be updated.")

        fs.unlinkSync(filename, function(error) {
            if(error) throw error;
            console.log("2. " + filename + " is been unlinked from server.");
        });

    } else {
        console.log("1. " + filename + " not found.");
        console.log("2. Server needs to be configured.");
    }
});

fs.openSync(filename, "w+", function(error) {
    if(error) throw error;
    console.log("3. " + filename + " file is been locked.");
}); 

fs.writeFileSync(filename, serverData, function(error) {
    if(error) throw error;
    console.log("4. " + filename + " is now updated.");

    fs.readFileSync(filename, 'utf-8', function(error, data) {
        if(error) throw error;

        console.log("5. Reading " + filename + " file");
        console.log("6. " + filename + " contents are below\n");
        console.log(data);
        console.log("-------THE END OF FILE-------");
    });
});

I have edited the code and added sync but now its giving me following error:

D:\NodeJS\fs>node eg5.js

buffer.js:382
      throw new Error('Unknown encoding');
            ^
Error: Unknown encoding
    at Buffer.write (buffer.js:382:13)
    at new Buffer (buffer.js:261:26)
    at Object.fs.writeFileSync (fs.js:758:12)
    at Object.<anonymous> (D:\NodeJS\fs\eg5.js:28:4)
    at Module._compile (module.js:449:26)
    at Object.Module._extensions..js (module.js:467:10)
    at Module.load (module.js:356:32)
    at Function.Module._load (module.js:312:12)
    at Module.runMain (module.js:492:10)
    at process.startup.processNextTick.process._tickCallback (node.js:244:9)

D:\NodeJS\fs>

Is there anything wrong in my code regarding utf8 !

Ashwin Hegde
  • 1,733
  • 4
  • 19
  • 49

1 Answers1

1

You're calling asynchronous versions of the fs object and passing callbacks.

Synchronous versions also exist. For example, see : Check synchronously if file/directory exists in Node.js

In your original code before editing to sync:

    fs.writeFile(filename, serverData, function(error) {
        ...
    });

    fs.readFile(filename, "utf-8", function(error, data) {

The second argument to that call is a callback. It will asynchronously run the exists check and call the function you passed in when done. fs.readfile will immediately get called before writeFile finishes.

If you're goal is to write node async code, then nest the read call inside the write callback. If you're goal is to write a straightforward synchronous script then switch to the synchronous calls and write flat code.

If you're writing server code with node.js, it's critical that you use all async I/O calls since it's one thread on a loop. If you're just writing a script like above and want it to be simple in synchronous order, use the sync versions of the API.

Since node should be async, sync calls are the exception so the convention is to end the function name with sync. Thus functions like fs.existsSync

Community
  • 1
  • 1
bryanmac
  • 38,941
  • 11
  • 91
  • 99
  • i have now replaced fs.exists with fs.existsSync and when i am running node it is not showing me any message! Do i need some delay function here to hold my output? – Ashwin Hegde May 10 '13 at 12:31
  • 1
    Did you switch all fs calls to sync and stop nesting code in callbacks. If you write sync code, then it should be written flat. – bryanmac May 10 '13 at 12:35
  • 1
    But if you're goal is to learn node and write async code then nest read file inside the write file callback. I'll edit. – bryanmac May 10 '13 at 12:39
  • ok thanks. I have updated my information. please have a look on my question. – Ashwin Hegde May 10 '13 at 12:57
  • 1
    I think that's a separate question and no longer about understanding flow, async, sync. To keep SO useful, should probably just ask another question and pull that out of the edit. – bryanmac May 10 '13 at 13:00