读取Node.js中的文件


186

我对在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与尝试打开并读取它的文件位于同一目录中。

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

{[错误:ENOENT,打开'./start.html']错误号:34,代码:'ENOENT',路径:'./ start.html'}

有任何想法吗?


8
文件可能不在您/代码认为的位置。如果文件与脚本位于同一目录,请尝试:path.join(__dirname, 'start.html')
dc5

1
您可以console.log(“ __ dirname:” + __dirname); 在输出err之前?这将告诉您此时可执行文件所在的目录是本地的。您可以做一些事情来更改位置,也许您遇到了麻烦,也许代码不在您认为的__dirname处运行。
布赖恩

该文件必须与运行节点进程所在的目录相同。因此,如果文件位于dir / node / index.html中,而您的app.js文件也位于目录中,但是您这样做:node /dir/node/app.js然后,您将收到错误消息。dc5的解决方案应该可以解决问题。
埃文·肖蒂斯

您应该关闭此问题,或提供您的编辑作为答案并接受。
ChrisCM 2013年

使用path.join(__dirname, '/filename.html')并从stackoverflow.com/a/56110874/4701635中
Paresh Barad,

Answers:


237

使用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。


14
@AramKocharyan切勿在异步代码中使用* Sync函数。这将锁定整个应用程序,直到读取文件为止。*同步功能旨在在应用启动时使用,例如在模块系统中。
Eugene Kostrikov 2014年

3
是的,在我看来,这是一项艰巨的任务。
Aram Kocharyan 2014年

2
还有就是你的代码示例中一个错字的错误,你path.join是无用的,使用,的,而不是+
伊夫·M.

该代码似乎对我不起作用,我仍然遇到相同的错误
aiden87 '16

为什么仅使用一个普通的字符串路径就不能正常工作,例如../someFolder/myFile.txt
米格尔·佩雷斯(MiguelPéres)

42

使用Node 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()返回Buffer或字符串(如果您要求)。

fs正确假设相对路径是安全问题。 path是一种解决方法。

要以字符串形式加载,请指定编码:

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

5
*Sync为网络编程时请勿使用任何方法。这些仅适用于Grunt / gulp任务,控制台应用程序等。它们在阅读时暂停整个过程。OP的代码引用,response因此显然readFileSync是不合适的Web应用程序。
塞缪尔·内夫

3
无论是否存在其他用例(并且在启动时将文件加载到缓存中绝对不是其中一种),OP的帖子绝对不是您要使用readFileSync的情况-他在处理过程中一个网络请求。这个答案完全不适合眼前的问题。
塞缪尔·内夫

28

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)。对于同步:

var fs = require('fs');
var path = process.cwd();
var buffer = fs.readFileSync(path + "\\text.txt");
console.log(buffer.toString());

3
代替process.cwd()我认为您可以使用__dirname变量
Ishikawa Yoshi

2
@IshikawaYoshi process.cwd()是当前的工作目录,并且__dirname是当前模块的目录,因此它们不相同。
A1rPun

13

与节点的简单同步方式:

let fs = require('fs')

let filename = "your-file.something"

let content = fs.readFileSync(process.cwd() + "/" + filename).toString()

console.log(content)

9

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

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());

5

使用http模块从服务器读取html文件。这是从服务器读取文件的一种方法。如果要在控制台上获取它,只需删除http模块声明即可。

var http = require('http');
var fs = require('fs');
var server = http.createServer(function(req, res) {
  fs.readFile('HTMLPage1.html', function(err, data) {
    if (!err) {
      res.writeHead(200, {
        'Content-Type': 'text/html'
      });
      res.write(data);
      res.end();
    } else {
      console.log('error');
    }
  });
});
server.listen(8000, function(req, res) {
  console.log('server listening to localhost 8000');
});
<html>

<body>
  <h1>My Header</h1>
  <p>My paragraph.</p>
</body>

</html>


上面的代码是读取服务器上的html文件。您可以通过使用“ http”模块创建服务器来读取服务器上的html文件。这是在服务器上响应文件的方法。您也可以删除“ http”模块以在控制台上获取它
Aaditya

1
嘿,您可能想通过单击“编辑”按钮在评论中添加评论。
格伦·沃森

3

如果您想知道如何在目录中读取文件,并对其进行操作,那么就可以开始。这也向您展示了如何通过来运行命令power shell。这是在TypeScript!我遇到了麻烦,所以希望有一天能对某人有所帮助。如果您认为这无济于事,请随意对我投反对票。这是什么为我做的是webpack我所有的.ts在每个特定的文件夹内,我的目录文件来准备部署。希望您可以使用它!

import * as fs from 'fs';
let path = require('path');
let pathDir = '/path/to/myFolder';
const execSync = require('child_process').execSync;

let readInsideSrc = (error: any, files: any, fromPath: any) => {
    if (error) {
        console.error('Could not list the directory.', error);
        process.exit(1);
    }

    files.forEach((file: any, index: any) => {
        if (file.endsWith('.ts')) {
            //set the path and read the webpack.config.js file as text, replace path
            let config = fs.readFileSync('myFile.js', 'utf8');
            let fileName = file.replace('.ts', '');
            let replacedConfig = config.replace(/__placeholder/g, fileName);

            //write the changes to the file
            fs.writeFileSync('myFile.js', replacedConfig);

            //run the commands wanted
            const output = execSync('npm run scriptName', { encoding: 'utf-8' });
            console.log('OUTPUT:\n', output);

            //rewrite the original file back
            fs.writeFileSync('myFile.js', config);
        }
    });
};

// loop through all files in 'path'
let passToTest = (error: any, files: any) => {
    if (error) {
        console.error('Could not list the directory.', error);
        process.exit(1);
    }

    files.forEach(function (file: any, index: any) {
        let fromPath = path.join(pathDir, file);
        fs.stat(fromPath, function (error2: any, stat: any) {
            if (error2) {
                console.error('Error stating file.', error2);
                return;
            }

            if (stat.isDirectory()) {
                fs.readdir(fromPath, (error3: any, files1: any) => {
                    readInsideSrc(error3, files1, fromPath);
                });
            } else if (stat.isFile()) {
                //do nothing yet
            }

        });
    });
};

//run the bootstrap
fs.readdir(pathDir, passToTest);

2
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);
  }
});
By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.