IT story

Node.js에서 파일 읽기

hot-time 2020. 6. 14. 09:48
반응형

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이 열려고하는 파일과 동일한 디렉토리에 있습니다.

그러나 콘솔에서 나는 얻는다 :

{[오류 : ENOENT, './start.html'열기] 오류 : 34, 코드 : 'ENOENT', 경로 : './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 덕분입니다.


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

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

노드와 간단한 동기 방식 :

let fs = require('fs')

let filename = "your-file.something"

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

console.log(content)

이 코드를 실행하면 파일에서 데이터를 가져 와서 콘솔에 표시합니다

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

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

If you want to know how to read a file, within a directory, and do something with it, here you go. This also shows you how to run a command through the power shell. This is in TypeScript! I had trouble with this, so I hope this helps someone one day. Feel free to down vote me if you think its THAT unhelpful. What this did for me was webpack all of my .ts files in each of my directories within a certain folder to get ready for deployment. Hope you can put it to use!

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

To read the html file from server using http module. This is one way to read file from server. If you want to get it on console just remove http module declaration.

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>

참고URL : https://stackoverflow.com/questions/18386361/read-a-file-in-node-js

반응형