hjm*_*hjm 1 javascript node.js
我是node的初学者,我想通过读取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)
});
Run Code Online (Sandbox Code Playgroud)
在此行下,我要阅读的文本文件是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
Run Code Online (Sandbox Code Playgroud)
每次我运行程序和console.log内容时,都会遇到相同的错误
Run Code Online (Sandbox Code Playgroud)(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)
感谢您提出的错误建议,谢谢
这个:
var filename = require("../films.txt");
Run Code Online (Sandbox Code Playgroud)
应该是这样的:
var filename = "../films.txt";
Run Code Online (Sandbox Code Playgroud)
filename应该是文件的路径。require用于加载模块(有效的JavaScript代码而不是影片列表)。
| 归档时间: |
|
| 查看次数: |
770 次 |
| 最近记录: |