2017-02-02 64 views
0

我是節點的初學者,我想創建 從讀取txt文件的列表數據結構,這裏是我的代碼來讀取文件。當讀取節點中的txt文件時出現意外的標識符

 var fs = require("fs"); 
     var filename = require("../films.txt"); 

     fs.readFile(filename, 'utf8', function(err,data){ 
      var contents = data; 
      var splitContents = contents.split("\n"); 
      var string = JSON.stringify(splitContents); 
      console.log(string) 
     }); 

並且在這行下面是我想要讀取的文本文件是20個電影,文件的名稱是films.txt。

1. The Shawshank Redemption 
    2. The Godfather 
    3. The Godfather: Part II 
    4. Pulp Fiction 
    5. The Good, the Bad and the Ugly 
    6. 12 Angry Men 
    7. Schindler’s List 
    8. The Dark Knight 
    9. The Lord of the Rings: The Return of the King 
    10. Fight Club 
    11. Star Wars: Episode V - The Empire Strikes Back 
    12. One Flew Over the Cuckoo’s Nest 
    13. The Lord of the Rings: The Fellowship of the Ring 
    14. Inception 
    15. Goodfellas 
    16. Star Wars 
    17. Seven Samurai 
    18. The Matrix 
    19. Forrest Gump 
    20. City of God 

我每次運行程序和CONSOLE.LOG我得到同樣的錯誤

(function (exports, require, module, __filename, __dirname) { 1. The Shawshank Redemption 

                   ^^^ 

SyntaxError: Unexpected identifier 

    at Object.exports.runInThisContext (vm.js:76:16) 

    at Module._compile (module.js:542:28) 

    at Object.Module._extensions..js (module.js:579:10) 

    at Module.load (module.js:487:32) 

    at tryModuleLoad (module.js:446:12) 

    at Function.Module._load (module.js:438:3) 

    at Module.require (module.js:497:17) 

    at require (internal/module.js:20:19) 

我會明白什麼我做錯了反饋的內容,謝謝

+0

當你在runstack中看到_compile時,它表示一個語法問題,這意味着你的javascript沒有正確形成(缺少括號等)。 – rasmeister

回答

4

此:

var filename = require("../films.txt"); 

應該是這樣的:

var filename = "../films.txt"; 

filename路徑應該到您的文件。 require用於加載模塊(這是有效的JavaScript代碼不是電影列表)。

+0

謝謝你的工作! – hjm

2

require加載文件就好像它是Javascript代碼,試圖運行它。你的文本文件不是Javascript代碼。你只是想這樣做:

var fs = require("fs"); 
    var filename = "../films.txt"; 

    fs.readFile(filename, 'utf8', function(err,data){ 
     // ... 
+0

謝謝你,這也工作得很好! – hjm