search
HomeWeb Front-endJS TutorialTechnical answers to global objects and global variables in js and the file system

node全局对象是js中的一个对象,该对象又称为为全局对象。在客户端中,该对象为whindow,由this进行指向ode中的全局对象为global,所有的全局变量,除了自己以外都是global对象的属性

全局对象和全局变量

全局变量是全局对象的宿主

_filename

表示当前正在执行的脚本名,将会输出文件位置所在的绝对路径。
如果在模块中,返回的是模块文件的路径。

PS C:\Users\mingm\Desktop\test> node main.js
C:\Users\mingm\Desktop\test\main.js
PS C:\Users\mingm\Desktop\test>
// 输出全局变量 __filename的值
console.log(__filename);

__dirname

表示当前执行脚本所在的目录

PS C:\Users\mingm\Desktop\test> node main.js
C:\Users\mingm\Desktop\test
PS C:\Users\mingm\Desktop\test>
console.log(__dirname);

setTimeout

function printHello() {
    console.log('hello word');
};

// 两秒后执行以上函数
setTimeout(printHello, 2000);    // 该函数返回一个代表定时器的句柄值
function printHello() {
    console.log('hello word');
};

// 两秒后执行以上函数
setTimeout(printHello, 2000);    // 该函数返回一个代表定时器的句柄值

clearTimeout

停止一个计时器

settlnterval

一个计时器会不断的调用,返回的是一个代表定时器的句柄值

function printHello() {
    console.log('hello word!');
};

// 每两秒后循环执行以上函数
setInterval(printHello, 2000);
PS C:\Users\mingm\Desktop\test> node main.js
hello word!
hello word!
hello word!
hello word!
hello word!
hello word!
hello word!
hello word!
hello word!

process

一个全局变量,即global对象的属性
用于描述当前node进程状态的对象。

process.on('exit', (code) => {
    // 下方代码不会执行
    setTimeout(() => {console.log('该代码不会执行');}, 0);

    console.log('退出码为', code);
});
console.log('程序执行结束');
PS C:\Users\mingm\Desktop\test> node main.js
程序执行结束
退出码为 0
PS C:\Users\mingm\Desktop\test>

一个示例文件

// 输出到终端
process.stdout.write('hello world!' + '\n');    // 创建一个写入流,通过写入流,输出到终端

// 通过参数读取
process.argv.forEach((val, index, array) => {console.log(val + index + array)});

// 获取执行路径
console.log(process.execPath);

// 平台信息
console.log(process.platform);
PS C:\Users\mingm\Desktop\test> node main.js
hello world!
C:\Program Files\nodejs\node.exe0C:\Program Files\nodejs\node.exe,C:\Users\mingm\Desktop\test\main.js
C:\Users\mingm\Desktop\test\main.js1C:\Program Files\nodejs\node.exe,C:\Users\mingm\Desktop\test\main.js
C:\Program Files\nodejs\node.exe
win32
PS C:\Users\mingm\Desktop\test>
PS C:\Users\mingm\Desktop\test> node main.js
{ rss: 18874368,
  heapTotal: 6066176,
  heapUsed: 3677376,
  external: 8272 }
PS C:\Users\mingm\Desktop\test>
// 输出内存使用情况
console.log(process.memoryUsage());

node文件系统

node提供一组类似unix的标准文件操作api

异步和同步

异步的方法后面会有一个回调函数

貌似回调多了以后会产生回调地狱
var fs = require('fs');

// 异步读取
fs.readFile('input.txt', (err, data) => { err?console.error(err):true;
    console.log('异步读取' + data.toString());
});
PS C:\Users\mingm\Desktop\test> node main.js
异步读取33333333333333333333333333333333333333333
PS C:\Users\mingm\Desktop\test>
ps 减少异步,让世界更美好一点(^o^)/
建议回调使用箭头函数,要不然很容易产生回调地狱,让人抓狂

打开文件

// 打开input.txt文件进行读写
var fs = require('fs');

// 异步打开文件
console.log('准备打开文件!');
fs.open('input.txt', 'r+', (err, fd) => {err?console.log(err):console.log('文件打开成功!');});
PS C:\Users\mingm\Desktop\test> node main.js
准备打开文件!
文件打开成功!

获取文件信息

fs模块下的stat方法
判断是否是文件

var fs = require('fs');

fs.stat('input.txt', (err, stats) => {console.log(stats.isFile());});
PS C:\Users\mingm\Desktop\test> node main.js
true
PS C:\Users\mingm\Desktop\test>
var fs = require('fs');

console.log('准备打开文件!');
fs.stat('input.txt', (err, stats) => {err?console.log(err):console.log(stats);
    console.log('读取文件信息成功!');
    // 检测文件类型
    console.log(stats.ifFile());
    console.log(stats.isDirectory());
});
PS C:\Users\mingm\Desktop\test> node main.js
准备打开文件!
Stats {
  dev: 982976588,
  mode: 33206,
  nlink: 1,
  uid: 0,
  gid: 0,
  rdev: 0,
  blksize: undefined,
  ino: 12103423998567884,
  size: 41,
  blocks: undefined,
  atimeMs: 1532607165034.9072,
  mtimeMs: 1532606924599.2798,
  ctimeMs: 1532606924599.2798,
  birthtimeMs: 1532606914067.3428,
  atime: 2018-07-26T12:12:45.035Z,
  mtime: 2018-07-26T12:08:44.599Z,
  ctime: 2018-07-26T12:08:44.599Z,
  birthtime: 2018-07-26T12:08:34.067Z }
读取文件信息成功!
C:\Users\mingm\Desktop\test\main.js:7
        console.log(stats.ifFile());
                          ^

TypeError: stats.ifFile is not a function
    at fs.stat (C:\Users\mingm\Desktop\test\main.js:7:20)
    at FSReqWrap.oncomplete (fs.js:159:5)
PS C:\Users\mingm\Desktop\test>

写入文件

var fs = require('fs');

console.log('准备写入文件');
fs.writeFile('input.txt', '我是异步写入的内容', (err) => { err?console.log(err):false;
    console.log('数据写入成功!');
    console.log('----我是分割线----');
    console.log('开始读取写入的数据');
    fs.readFile('input.txt', (err, data) => {
        err?console.log(err):false;
        console.log('异步读取数据为' + data.toString());
    });
});
PS C:\Users\mingm\Desktop\test> node main.js
准备写入文件
数据写入成功!
----我是分割线----
开始读取写入的数据
异步读取数据为我是异步写入的内容
PS C:\Users\mingm\Desktop\test>

读取文件

在异步的情况下读取文件
参数 http://nodejs.cn/api/fs.html#...
使用的fs.read http://nodejs.cn/api/fs.html#...

var fs = require('fs');
var buf = new Buffer.alloc(1024);    // 创建一个缓冲区

console.log('准备打开已存在的文件');
fs.open('input.txt', 'r+', (err, fd) => {
    if (err) {
        console.log(err);
    };
    console.log('文件打开成功');
    console.log('准备读取文件');
    fs.read(fd, buf, 0, buf.length, 0, (err, bytes) => {
        if (err) {
            console.log(err);
        };
        console.log(bytes + '字节被读取');

        // 输出读取的字节
        if (buyes > 0) {
            console.log(buf.slice(0, bytes).toString());
        }
    });
});
PS C:\Users\mingm\Desktop\test> node main.js
准备写入文件
数据写入成功!
----我是分割线----
开始读取写入的数据
异步读取数据为我是异步写入的内容
PS C:\Users\mingm\Desktop\test>

Buffer.slice http://nodejs.cn/api/buffer.html
返回一个指向相同原始内存的新建的 Buffer

PS C:\Users\mingm\Desktop\test> node main.js
准备打开已存在的文件
文件打开成功
准备读取文件
27字节被读取
我是异步写入的内容
PS C:\Users\mingm\Desktop\test>
var fs = require('fs');
var buf = new Buffer.alloc(1024);    // 创建一个缓冲区

console.log('准备打开已存在的文件');
fs.open('input.txt', 'r+', (err, fd) => {
    if (err) {
        return console.log(err);
    };
    console.log('文件打开成功');
    console.log('准备读取文件');
    fs.read(fd, buf, 0, buf.length, 0, (err, bytes) => {
        if (err) {
            console.log(err);
        };
        console.log(bytes + '字节被读取');

        // 输出读取的字节
        if (bytes > 0) {
            console.log(buf.slice(0, bytes).toString());
        }
    });
});

关闭文件

在异步的模式下关闭文件

PS C:\Users\mingm\Desktop\test> node main.js
准备打开文件!
文件打开成功!
准备读取文件!
我是异步写入的内容
文件关闭成功
PS C:\Users\mingm\Desktop\test>
var fs = require('fs');
var buf = new Buffer.alloc(1024);


console.log('准备打开文件!');
fs.open('input.txt', 'r+', (err, fd) => {
    if (err) {
        return console.log(err);
    };
    console.log('文件打开成功!');
    console.log('准备读取文件!');
    fs.read(fd, buf, 0, buf.length, 0, (err, bytes) => {
        if (err) {
            console.log(err);
        };

        // 输出能读取的字节
        if(bytes > 0) {
            console.log(buf.slice(0,bytes).toString());
        };

        // 关闭文件
        fs.close(fd, (err) => {
            if(err) {
                console.log(err);
            };
            console.log('文件关闭成功');
        });
    });
});

截取文件

在异步的模式下截取文件
fs.ftruncate(fd[, len], callback)
http://nodejs.cn/api/fs.html#...

var fs = require('fs');
var buf = new Buffer.alloc(1024);

console.log('准备打开文件!');
fs.open('input.txt', 'r+', (err, fd) => {
    if (err) {
        return console.error(err);
    };
    console.log('文件打开成功!');
    console.log('截取了10字节后的文件内容。');

    // 截取文件
    fs.ftruncate(fd, 10, (err) => {
        if (err) {
            console.log(err);
        };
        console.log('文件截取成功');
        console.log('读取相同的文件');
        fs.read(fd, buf, 0, buf.length, 0, (err, bytes) => {
            if (err) {
                console.log(err);
            };

            // 仅输出读取的字节
            if (bytes > 0) {
                console.log(buf.slice(0, bytes).toString());
            }

            // 关闭文件
            fs.close(fd, (err) => {
                console.log(err);
            });
            console.log('文件关闭成功!');
        });
    });
});
PS C:\Users\mingm\Desktop\test> node main.js
准备打开文件!
文件打开成功!
截取了10字节后的文件内容。
文件截取成功
读取相同的文件
我是异�
文件关闭成功!
null
PS C:\Users\mingm\Desktop\test>

删除文件

PS C:\Users\mingm\Desktop\test> node main.js
准备删除文件!
文件删除成功!
PS C:\Users\mingm\Desktop\test>
var fs = require('fs');

console.log('准备删除文件!')
fs.unlink('input.txt', (err) => {
    if (err) {
        return console.log(err);
    };
    console.log('文件删除成功!');
});

创建目录

PS C:\Users\mingm\Desktop\test> node main.js
创建目录 ./tmp/test
{ [Error: ENOENT: no such file or directory, mkdir 'C:\Users\mingm\Desktop\test\tmp\test']
  errno: -4058,
  code: 'ENOENT',
  syscall: 'mkdir',
  path: 'C:\\Users\\mingm\\Desktop\\test\\tmp\\test' }
PS C:\Users\mingm\Desktop\test>
var fs = require('fs');

console.log('创建目录 ./tmp/test');
fs.mkdir('./tmp/test', (err) => {
    if (err) {
        return console.log(err);
    };
    console.log('目录创建成功!');
});

读取目录

forEach方法没有找到一个 官方文档,貌似目前找不到

PS C:\Users\mingm\Desktop\test> node main.js
查看 /tmp 目录
{ [Error: ENOENT: no such file or directory, scandir 'C:\Users\mingm\Desktop\test\tmp']
  errno: -4058,
  code: 'ENOENT',
  syscall: 'scandir',
  path: 'C:\\Users\\mingm\\Desktop\\test\\tmp' }
PS C:\Users\mingm\Desktop\test>
var fs = require('fs');

console.log('查看 /tmp 目录');
fs.readdir('./tmp/', (err, files) => {
    if (err) {
        return console.log(err);
    };
    files.forEach((file) => {    // 这个方法目前没有找到,联系到客户端的方法,貌似是合并的意思
        console.log( file );    
    });
});

相关文章:

全局对象_php教程

Node.js 全局对象

什么是JavaScript全局对象?全局对象有哪些属性?

相关视频:

Nodejs + mongoDB实战开发微博系统视频教程

The above is the detailed content of Technical answers to global objects and global variables in js and the file system. For more information, please follow other related articles on the PHP Chinese website!

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Javascript Data Types : Is there any difference between Browser and NodeJs?Javascript Data Types : Is there any difference between Browser and NodeJs?May 14, 2025 am 12:15 AM

JavaScript core data types are consistent in browsers and Node.js, but are handled differently from the extra types. 1) The global object is window in the browser and global in Node.js. 2) Node.js' unique Buffer object, used to process binary data. 3) There are also differences in performance and time processing, and the code needs to be adjusted according to the environment.

JavaScript Comments: A Guide to Using // and /* */JavaScript Comments: A Guide to Using // and /* */May 13, 2025 pm 03:49 PM

JavaScriptusestwotypesofcomments:single-line(//)andmulti-line(//).1)Use//forquicknotesorsingle-lineexplanations.2)Use//forlongerexplanationsorcommentingoutblocksofcode.Commentsshouldexplainthe'why',notthe'what',andbeplacedabovetherelevantcodeforclari

Python vs. JavaScript: A Comparative Analysis for DevelopersPython vs. JavaScript: A Comparative Analysis for DevelopersMay 09, 2025 am 12:22 AM

The main difference between Python and JavaScript is the type system and application scenarios. 1. Python uses dynamic types, suitable for scientific computing and data analysis. 2. JavaScript adopts weak types and is widely used in front-end and full-stack development. The two have their own advantages in asynchronous programming and performance optimization, and should be decided according to project requirements when choosing.

Python vs. JavaScript: Choosing the Right Tool for the JobPython vs. JavaScript: Choosing the Right Tool for the JobMay 08, 2025 am 12:10 AM

Whether to choose Python or JavaScript depends on the project type: 1) Choose Python for data science and automation tasks; 2) Choose JavaScript for front-end and full-stack development. Python is favored for its powerful library in data processing and automation, while JavaScript is indispensable for its advantages in web interaction and full-stack development.

Python and JavaScript: Understanding the Strengths of EachPython and JavaScript: Understanding the Strengths of EachMay 06, 2025 am 12:15 AM

Python and JavaScript each have their own advantages, and the choice depends on project needs and personal preferences. 1. Python is easy to learn, with concise syntax, suitable for data science and back-end development, but has a slow execution speed. 2. JavaScript is everywhere in front-end development and has strong asynchronous programming capabilities. Node.js makes it suitable for full-stack development, but the syntax may be complex and error-prone.

JavaScript's Core: Is It Built on C or C  ?JavaScript's Core: Is It Built on C or C ?May 05, 2025 am 12:07 AM

JavaScriptisnotbuiltonCorC ;it'saninterpretedlanguagethatrunsonenginesoftenwritteninC .1)JavaScriptwasdesignedasalightweight,interpretedlanguageforwebbrowsers.2)EnginesevolvedfromsimpleinterpreterstoJITcompilers,typicallyinC ,improvingperformance.

JavaScript Applications: From Front-End to Back-EndJavaScript Applications: From Front-End to Back-EndMay 04, 2025 am 12:12 AM

JavaScript can be used for front-end and back-end development. The front-end enhances the user experience through DOM operations, and the back-end handles server tasks through Node.js. 1. Front-end example: Change the content of the web page text. 2. Backend example: Create a Node.js server.

Python vs. JavaScript: Which Language Should You Learn?Python vs. JavaScript: Which Language Should You Learn?May 03, 2025 am 12:10 AM

Choosing Python or JavaScript should be based on career development, learning curve and ecosystem: 1) Career development: Python is suitable for data science and back-end development, while JavaScript is suitable for front-end and full-stack development. 2) Learning curve: Python syntax is concise and suitable for beginners; JavaScript syntax is flexible. 3) Ecosystem: Python has rich scientific computing libraries, and JavaScript has a powerful front-end framework.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Linux new version

SublimeText3 Linux new version

SublimeText3 Linux latest version

MantisBT

MantisBT

Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.