简体   繁体   English

需要了解NodeJS中ReadWrite的流程

[英]Need to Understand the flow of ReadWrite in NodeJS

I am just trying some code on NodeJS, i am new to NodeJS. 我只是在NodeJS上尝试一些代码,我是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 D:\\ NodeJS \\ fs>节点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 ! 关于utf8,我的代码有什么问题!

You're calling asynchronous versions of the fs object and passing callbacks. 您正在调用fs对象的异步版本并传递回调。

Synchronous versions also exist. 同步版本也存在。 For example, see : Check synchronously if file/directory exists in Node.js 例如,请参阅: 同步检查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. 它将异步运行exists检查并在完成后调用您传入的函数。 fs.readfile will immediately get called before writeFile finishes. 在writeFile完成之前,将立即调用fs.readfile。

If you're goal is to write node async code, then nest the read call inside the write callback. 如果你的目标是编写节点异步代码,那么将read调用嵌套在write回调中。 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. 如果您正在使用node.js编写服务器代码,那么使用所有异步I / O调用至关重要,因为它是循环中的一个线程。 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. 如果您只是编写如上所述的脚本并希望它以同步顺序简单,请使用API​​的同步版本。

Since node should be async, sync calls are the exception so the convention is to end the function name with sync. 由于节点应该是异步的,因此同步调用是例外,因此惯例是使用sync结束函数名称。 Thus functions like fs.existsSync 因此像fs.existsSync这样的函数

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM