在Node.js中读取一个文件

时间:2022-02-16 23:13:14

I'm quite puzzled with reading files in 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);
    }
});

File start.html is in the same directory with file that tries to open and read it.

文件开始。html与试图打开和读取它的文件位于同一个目录中。

However, in the console I get:

然而,在控制台我得到:

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

{[错误:ENOENT, open './start。[html] errno: 34,代码:'ENOENT', path: './开始。html的}

Any ideas?

什么好主意吗?

5 个解决方案

#1


121  

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

使用路径。加入(__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);
    }
});

Thanks to dc5.

感谢dc5。

#2


26  

With Node 0.12, it's possible to do this synchronously now:

对于节点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 is the file system. readFileSync() returns a Buffer, or string if you ask.

fs是文件系统。readFileSync()返回一个缓冲区或字符串。

fs correctly assumes relative paths are a security issue. path is a work-around.

fs正确地假定相对路径是一个安全问题。路径是一个变通方法。

To load as a string, specify the encoding:

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

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

#3


10  

1).For ASync :

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).For Sync :

2)因为同步:

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

#4


1  

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

#5


0  

Run this code, it will fetch data from file and display in console

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

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

#1


121  

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

使用路径。加入(__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);
    }
});

Thanks to dc5.

感谢dc5。

#2


26  

With Node 0.12, it's possible to do this synchronously now:

对于节点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 is the file system. readFileSync() returns a Buffer, or string if you ask.

fs是文件系统。readFileSync()返回一个缓冲区或字符串。

fs correctly assumes relative paths are a security issue. path is a work-around.

fs正确地假定相对路径是一个安全问题。路径是一个变通方法。

To load as a string, specify the encoding:

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

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

#3


10  

1).For ASync :

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).For Sync :

2)因为同步:

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

#4


1  

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

#5


0  

Run this code, it will fetch data from file and display in console

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

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