220

我对在 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'] errno:34,代码:'ENOENT',路径:'./start.html'}

有任何想法吗?

4

8 回答 8

279

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

于 2013-11-01T07:13:08.430 回答
53

使用 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()返回一个缓冲区或字符串。

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

要作为字符串加载,请指定编码:

return fs.readFileSync(path,{ encoding: 'utf8' });
于 2015-04-26T04:10:08.647 回答
35

1).对于异步:

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());
于 2016-10-23T07:21:14.470 回答
24

与节点的简单同步方式:

let fs = require('fs')

let filename = "your-file.something"

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

console.log(content)
于 2019-05-12T15:22:44.747 回答
18

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

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());
于 2016-09-23T07:26:55.577 回答
6

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>

于 2019-09-15T08:44:22.563 回答
4

如果您想知道如何在目录中读取文件并对其进行处理,那么就可以了。这也向您展示了如何通过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);
于 2018-11-16T15:07:28.393 回答
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);
  }
});
于 2013-11-22T11:27:59.810 回答