2016-04-22 3 views
0

NodeJSでChromeのmaster_preferencesファイルを読み込もうとしています。私は、次の試みを試してみた:master_preferencesを読み込むときのrequire()とJSON.parse()の違い

require('./master_preferences') 

が動作しない動作しない(ファイルがfile -IとUTF8で確認した)(私はcp master_preferences master_preferences.jsonを実行した場合)

JSON.parse(fs.readFileSync('master_preferences', 'utf8')); 

が作業を行い

require('./master_preferences.json') 

JSON.parse()はrequire()より厳密ですか? python 2.7はまたjson.load(f)

+0

JSON.parse()はエラーを送出しますか? '.json'ファイル拡張子がないので、最初の試みは機能しません。 [Here](https://nodejs.org/api/modules.html#modules_all_together)は、ファイル/モジュールのロード時に 'require()'が従うロジックです。 – dvlsg

+0

SyntaxError:予想外のトークンは、NodeJSからスローされるトークンです。ノードのバージョンは5.9.1です – David

答えて

2

require('./master_preferences')を使用して入力を解析することはできませんので、任意の拡張子なしでは動作しませんFWIWは、ノードが.js拡張子を持つ通常のJavaScriptファイルとしてそれを前提としていて、それをコンパイルしようとします。単なるjsonは有効なjs構文ではないので、エラーをスローします。

require('./master_preferences.json')があなたのために働いて以来、私は問題がBOM文字であると信じています。 Become require()は、ファイルを解析する前にBOM文字を取り除こうとします。 See source

function stripBOM(content) { 
    if (content.charCodeAt(0) === 0xFEFF) { 
    content = content.slice(1); 
    } 
    return content; 
} 
JSON.parse(stripBOM(fs.readFileSync('master_preferences', 'utf8'))); 
関連する問題