在Node.js中读取文件

我对Node.js中的文件感到困惑。

fs.open('./start.html', 'r', function(err, fileToRead){ if (!err){ fs.readFile(fileToRead, {encoding: 'utf-8'}, function(err,data){ if (!err){ console.log('received data: ' + data); response.writeHead(200, {'Content-Type': 'text/html'}); response.write(data); response.end(); }else{ console.log(err); } }); }else{ console.log(err); } }); 

文件start.html与文件在同一个目录下,试图打开并阅读它。

但是,在控制台,我得到:

{[Error:ENOENT,open'./start.html'] errno:34,code:'ENOENT',path:'./start.html'}

有任何想法吗?

使用path.join(__dirname, '/start.html') ;

 var fs = require('fs'), path = require('path'), filePath = path.join(__dirname, 'start.html'); fs.readFile(filePath, {encoding: 'utf-8'}, function(err,data){ if (!err) { console.log('received data: ' + data); response.writeHead(200, {'Content-Type': 'text/html'}); response.write(data); response.end(); } else { console.log(err); } }); 

感谢dc5。

使用节点0.12,现在可以同步执行此操作:

  var fs = require('fs'); var path = require('path'); // Buffer mydata var BUFFER = bufferFile('../public/mydata.png'); function bufferFile(relPath) { return fs.readFileSync(path.join(__dirname, relPath)); // zzzz.... } 

fs是文件系统。 readFileSync()返回一个缓冲区或string,如果你问。

fs正确地假设相对path是一个安全问题。 path是一个解决方法。

要作为string加载,请指定编码:

 return fs.readFileSync(path,{ encoding: 'utf8' }); 

1)。对于ASync:

 var fs = require('fs'); fs.readFile(process.cwd()+"\\text.txt", function(err,data) { if(err) console.log(err) else console.log(data.toString()); }); 

2).For同步:

 var fs = require('fs'); var path = process.cwd(); var buffer = fs.readFileSync(path + "\\text.txt"); console.log(buffer.toString()); 
 var fs = require('fs'); var path = require('path'); exports.testDir = path.dirname(__filename); exports.fixturesDir = path.join(exports.testDir, 'fixtures'); exports.libDir = path.join(exports.testDir, '../lib'); exports.tmpDir = path.join(exports.testDir, 'tmp'); exports.PORT = +process.env.NODE_COMMON_PORT || 12346; // Read File fs.readFile(exports.tmpDir+'/start.html', 'utf-8', function(err, content) { if (err) { got_error = true; } else { console.log('cat returned some content: ' + content); console.log('this shouldn\'t happen as the file doesn\'t exist...'); //assert.equal(true, false); } }); 

运行此代码,它将从文件中获取数据并在控制台中显示

 function fileread(filename){ var contents= fs.readFileSync(filename); return contents; } var fs =require("fs"); // file system var data= fileread("abc.txt"); //module.exports.say =say; //data.say(); console.log(data.toString());