将文本文件读入node.js

我刚开始使用node.js 这是我有史以来的第一次尝试,我无法从txt文件读取到Windows 7中的node.jsterminal。使用窗口中的Node.js应用程序,我键入“node sample.js”和sample.js和sample.txt文件位于桌面上的文件夹中,但node.exe应用程序不读取文件。 另外我不知道它将如何知道目录path任何见解? 这是我的代码:

var fs = require("fs"); console.log("Starting"); fs.readFile("sample.txt", function(error, data) { console.log("Contents of file: " + data); }); console.log("Carrying on executing"); 

你应该看看error参数(logging或抛出),看看有什么问题。 因为您使用的是相对path,所以会相对于当前的工作目录。

node.js文档 :

可以使用文件名的相对path,但请记住,此path将与process.cwd()相关。

你也应该知道,代码的最后一行实际上是首先执行(可能),因为readFile是asynchronous的。 (这是一个关键的node.js概念。)

尝试使用

 fs.readFile(__dirname + "/sample.txt", function(error, data) { 

__dirname实际上是你所在文件的当前目录。

您可能不执行相对于您的应用程序目录的节点。

最简单的是创build一个batch file来执行你的应用程序。 这样你就不需要不断地从命令提示符重新input相对path:

  1. 在桌面上的应用程序目录中创build一个“.bat”文件。
  2. 将batch file的内容编辑为:node sample.js
  3. 双击运行batch file