9

私はNodeJSでいくつかのコードを試しています.NodeJSは初めてです。次のコードブロックを書きました。

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-------");
    });
});

コードを編集して同期を追加しましたが、次のエラーが表示されます。

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>

utf8 に関する私のコードに何か問題がありますか?

4

2 に答える 2

8

readFileSyncコールバックを受け取りません。readFile代わりに使いたかったのでしょう。

についても同じ問題がありwriteFileSyncます。完了時に呼び出されるこれらのコールバックは、IO 関数を同期的に使用する場合は意味がありません。非同期関数を (「同期」を使用せずに) 使用することをお勧めします。異なる引数を取ることに注意してください。

また、ドキュメントには常に では"utf8"なくが記載されています"utf-8"。後者がサポートされているかどうかはわかりません。

于 2013-05-10T13:11:25.467 に答える
4

node.js API ドキュメントによると、writeFileSync は 3 つの引数を取ります。

  1. 書き込むファイル名
  2. ファイルに入れるデータ
  3. オプションを含むオプション オブジェクト。そのうちの 1 つはエンコーディングです。

コールバックはどこにも指定されていません。非同期バージョンのみがコールバックを受け取ります。

http://www.nodejs.org/api/fs.html#fs_fs_writefilesync_filename_data_options

writeFileSync ブロックの代わりにこれを試してください:

fs.writeFileSync(filename, serverData, { encoding: 'utf8'});
console.log("4. " + filename + " is now updated.");

var contents = fs.readFileSync(filename, 'utf8');
console.log("5. Reading " + filename + " file");
console.log("6. " + filename + " contents are below\n");
console.log(contents);
console.log("-------THE END OF FILE-------");
于 2013-05-10T13:17:10.597 に答える