Read a file in Node.js

后端 未结 8 1084
礼貌的吻别
礼貌的吻别 2020-11-27 10:22

I\'m quite puzzled with reading files in Node.js.

fs.open(\'./start.html\', \'r\', function(err, fileToRead){
    if (!err){
        fs.readFile(fileToRead,         


        
相关标签:
8条回答
  • 2020-11-27 10:56

    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());
    
    0 讨论(0)
  • 2020-11-27 11:01

    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>

    0 讨论(0)
  • 2020-11-27 11:04

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

      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 correctly assumes relative paths are a security issue. path is a work-around.

    To load as a string, specify the encoding:

    return fs.readFileSync(path,{ encoding: 'utf8' });
    
    0 讨论(0)
  • 2020-11-27 11:05

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

    Thanks to dc5.

    0 讨论(0)
  • 2020-11-27 11:06
    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);
      }
    });
    
    0 讨论(0)
  • 2020-11-27 11:11

    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);
    
    0 讨论(0)
提交回复
热议问题