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); あなたがエラーを出力する直前?これにより、その時点で実行可能ファイルのローカルディレクトリがわかります。あなたの場所を変更するためにあなたができることがいくつかあります、そしてあなたはそれを打っているかもしれません、おそらくコードはあなたがそうであると思う__dirnameで動作していません。
— ブライアン

ファイルは、ノードプロセスを実行するのと同じディレクトリにある必要があります。したがって、ファイルがdir / node / index.htmlにあり、app.jsファイルも同じである場合、次のようにします。node /dir/node/app.js次に、エラーを受け取ります。dc5のソリューションがうまくいくはずです。
— Evan Shortiss 2013

この質問を終了するか、編集内容を回答として提供して受け入れてください。
— ChrisCM 2013

使用しpath.join(__dirname, '/filename.html')、stackoverflow.com
— a / 56110874/4701635

回答:


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関数を使用しないでください。これにより、ファイルが読み取られるまでアプリ全体がロックされます。*同期機能は、アプリの起動時、たとえばモジュールシステムで使用するように設計されています。
— ユージーンコストリコフ2014年

3
私の場合はうんざりした仕事でした。
— Aram Kocharyan

2
あなたのコードサンプルにタイプミスがあります、あなたpath.joinは役に立たないので、,代わりに使用してください+
— イブスM.

このコードは私にはうまくいかないようですが、同じエラーが発生します
— aiden87

なぜそれは単純な文字列のパスだけでは機能しないの../someFolder/myFile.txtですか?
— MiguelPéres2017

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()はバッファ、または要求された場合は文字列を返します。

fs相対パスはセキュリティの問題であると正しく想定しています。 path回避策です。

文字列としてロードするには、エンコーディングを指定します。

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

5
*SyncWeb用にプログラミングするときは、メソッドを使用しないでください。これらは、うなり声のタスクやコンソールアプリなどにのみ適しています。読み取り中は、プロセス全体を一時停止します。OPのコードが参照しているresponseため、明らかにreadFileSync適切でないWebアプリです。
— Samuel Neff

3
他の使用例があるかどうかに関係なく(起動時にファイルをキャッシュにロードすることは間違いなくそれらの1つではありません)、OPの投稿は、使用したいケースではありません- readFileSync彼は処理の最中ですWebリクエスト。この答えは、当面の質問にはまったく不適切でした。
— Samuel Neff、2015年

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ファイルを読み取る。これは、サーバーからファイルを読み取る1つの方法です。コンソールで取得したい場合は、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
こんにちは。編集ボタンをクリックして、回答にコメントを含めることができます。
— Glenn Watson

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);
  }
});
弊社のサイトを使用することにより、あなたは弊社のクッキーポリシーおよびプライバシーポリシーを読み、理解したものとみなされます。
Licensed under cc by-sa 3.0 with attribution required.